每次表单提交时都会创建重复记录MVC 4 C#

时间:2017-06-23 07:04:16

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

在MVC 4和Entity框架上工作,面对一个棘手的问题,在svind新记录之后我已经通过了Id来查看模型,但它仍然是相同的;(:

public ActionResult Edit(SubscriptionViewModel oSubModel) {
    if (ModelState.IsValid) {
        Subscription oSubDetail = new Subscription();
        oSubDetail.Title = oSubModel.Title;
        oSubDetail = this.subRep.SaveSubscription(oSubDetail);
        if (oSubDetail == null) {
            ModelState.AddModelError("error", "Error in saving the data,please try after some time.");
        } else {
            oSubModel.Id = oSubDetail.Id; //Id return to view
            ModelState.AddModelError("success", "User saved");
        }
    }
    }
    return View(oSubModel); //Model return to view 
    // Note: id that I've passed display here correct but in view its still 0
}


@using (Html.BeginForm()) {
    <div class="row">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
        @Html.HiddenFor(model => model.Id)
        <div class="col-md-6">
            <div class="form-group">
                @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label " })
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
                <a href="@Url.Action(" Subscription ", "Subscription ")" class="btn btn-default">
                        Back to Subscriptions
                </a>
            </div>
        </div>
    </div>
}

注意:在我传递的控制器ID中显示正确但在视图中仍为0

1 个答案:

答案 0 :(得分:0)

ID未发生变化,因为MVC在ModelState中查找最初提供给视图的值。为了防止这种情况,您需要删除ModelState

中的值
oSubModel.Id = oSubDetail.Id; //Id return to view
ModelState.Remove("Id");

现在已经解决了,当您第一次保存记录时,您将返回ID。但是,当您再次提交时,您并未使用该ID,因此会创建另一条记录。假设您的SaveSubscription函数检测到存在ID并更新记录而不是插入新记录,则需要将ID传递给它:

Subscription oSubDetail = new Subscription();
oSubDetail.Title = oSubModel.Title;
oSubDetail.Id = oSubModel.Id;
oSubDetail = this.subRep.SaveSubscription(oSubDetail);