从数据库添加数据后从哪里执行业务逻辑? (MVC)

时间:2015-05-27 19:47:40

标签: c# asp.net-mvc entity-framework

我在使用EntityFramework的MVC中有一个简单的CRUD应用程序。我需要在创建新元素后使用外部API,但我不确定从哪里做到这一点。

我已阅读本网站上的多个主题,其他人认为业务逻辑应该在模型中,而不是在Controller中,但是我不知道如何让它工作。

这就是我的模型:

public int ID { get; set; }

private string _name;
[Required(ErrorMessage = "Required")]
public string Name
{
    get { return _name; }
    set
    {
        _name= value;
        if (value != null)
        {
            this.doAPIStuff();
        }
    }
}
[Required(ErrorMessage = "Required")]
public string PersonalNumber { get; set; }

public void doAPIStuff()
{
    // do stuff
}

正如您所看到的,我在向数据库添加数据后尝试执行doAPIStuff()方法,但是当我在字段Name中输入内容时,我收到错误The value '<value>' is invalid(我在文本框中写的是什么。)

这些都没有帮助我解决我的问题:

The value “(string)” is invalid

ASP.NET MVC Page Validation Fails (The value is invalid.)

DropDownList Value is always invalid in MVC 3

我没有触及View - 这里的大部分内容都是:

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Person</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PersonalNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PersonalNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PersonalNumber, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

我在我的Controller中测试了来自doAPIStuff()的代码,所以我确定它确实有效,但我不知道如何运行它,如上所示。我想到的另一个选项是为doAPIStuff()方法创建一个新模型,但是我必须将NamePersonalNumber值传递给模型,这似乎是错误的要做的事。

0 个答案:

没有答案
相关问题