1
工作MVC 4和Entity Framework,面對後svind新紀錄我通過ID查看模型一個棘手的問題,但它的其餘相同;(:重複記錄創建每次表單提交MVC 4 C#
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
那他們存在(在你的情況下,他們這樣做)。行爲解釋在[這個答案](https://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111)。但是一旦數據被保存,你就不應該返回視圖。你應該重定向(PRG模式) –