[英]MVC model not binding on post
無法弄清楚我在做什么錯。 發布視圖中的表單后,模型屬性將變為空。
public class RegistrationModel
{
public RegistrationModel()
{
Registration = new REGISTRATION();
AddPayment = true;
}
public REGISTRATION Registration { get; set; }
public bool AddPayment { get; set; }
}
@model Client.Models.RegistrationModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(excludePropertyErrors: false)
<div class="form-group">
@Html.DropDownList("SECTION_ID", null, string.Empty, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.DropDownList("STUDENT_ID", null, string.Empty, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.DropDownList("STATUS_ID", null, string.Empty, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.CheckBoxFor(model => model.AddPayment)
</div>
<p>
<input type="submit" class="btn btn-success" value="Create" />
</p>
}
public ActionResult Create()
{
//code to populate view dropdowns
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(RegistrationModel model)
{
WriteFileLog(_logPath, Newtonsoft.Json.JsonConvert.SerializeObject(model));
}
在處理后模型的控制器的“創建”操作中,屬性為null。
注冊類(由EF從數據庫自動生成):
public partial class REGISTRATION
{
public REGISTRATION()
{
this.REGISTRATION_AUDIT = new HashSet<REGISTRATION_AUDIT>();
}
public int ID { get; set; }
public int SECTION_ID { get; set; }
public int STUDENT_ID { get; set; }
public int STATUS_ID { get; set; }
public virtual ICollection<REGISTRATION_AUDIT> REGISTRATION_AUDIT { get; set; }
public virtual SECTION SECTION { get; set; }
public virtual V_REGISTRATION_STATUS V_REGISTRATION_STATUS { get; set; }
public virtual PERSON PERSON { get; set; }
}
我建議使用強類型的幫助器,如下所示:
@Html.DropDownListFor(m => m.Registration.SECTION_ID, null, string.Empty, new { @class = "form-control" })
否則,您需要調整您要使用的名稱
@Html.DropDownList("Registration.SECTION_ID", null, string.Empty, new { @class = "form-control" })
您可以通過將Registration類的成員復制到視圖模型中,替換Registration屬性來簡化您的操作。
正如@StephenMuecke指出的那樣,您在模型/標記中缺少了一些部分。 您正在使用的DropDownList助手的模板是
DropDownListFor(
[model property to bind],
[collection of possible values to bind],
[option label],
[HTML attributes])
為第二個參數傳遞null意味着您沒有任何值可用來填充生成的<select>
元素,並且通常應生成一個異常。
我不喜歡使用ViewBag將集合傳遞到視圖中,因此我建議使用類似
public class RegistrationModel
{
public RegistrationModel()
{
Registration = new REGISTRATION();
AddPayment = true;
}
public REGISTRATION Registration { get; set; }
public bool AddPayment { get; set; }
public SelectList Sections { get; set; }
public SelectList Students { get; set; }
public SelectList Statuses { get; set; }
}
然后相應地調整標記:
@Html.DropDownListFor(m => m.Registration.SECTION_ID, Model.Sections, string.Empty, new { @class = "form-control" })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.