在我的示例MVC应用程序中,我有一个模型
class SampleModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<Certification> Certifications { get; set; }
}
class Certification
{
public int Id { get; set; }
public string CertificationName { get; set; }
public int DurationInMonths { get; set; }
}
我的视图(我需要在部分视图中显示认证详细信息)
@model SampleApplication.Model.SampleModel
<!-- other code... -->
@using (Html.BeginForm("SaveValues","Sample", FormMethod.Post, new { id= "saveForm" }))
{
@Html.HiddenFor(m => m.Id, new { id = "hdnID" })
@Html.TextBoxFor(m => m.Name, new { id = "txtName" })
@{Html.RenderPartial("_CertDetails.cshtml", Model.Certifications);}
<input type="submit" id="btnSubmit" name="btnSubmit" value="Update" />
}
局部视图
@model List<SampleApplication.Model.Certification>
<!-- other code... -->
@if (@Model != null)
{
for (int i = 0; i < @Model.Count; i++)
{
@Html.HiddenFor(m => m[i].Id , new { id = "CId" + i.ToString() })
@Html.TextBoxFor(m => m[i].CertificationName,new{ id ="CName" + i.ToString() })
@Html.TextBoxFor(m => m[i].DurationInMonths,new{ id ="CDur" + i.ToString() })
}
}
控制器[HttpPost]
public ActionResult SaveValues(SampleModel sm)
{
//Here i am not getting the updated Certification details (in sm)
}
我如何得到部分视图的更新值在我的控制器表单后?当我不使用partialview时,我能够获得更新的认证值。这是正确的方法还是我应该遵循其他方法?
如果sm.Certifications
返回null,这意味着要么没有发布任何内容,要么模型绑定器无法正确地附加发布的数据。
在您的部分中,您使用索引器正确地定义了字段,但最初,Certifications
是一个空列表,因此该代码从未实际运行。这意味着,在其他地方,您有一些JavaScript逻辑,动态地向页面添加新的Certification
字段,我的猜测是JavaScript生成的字段名不遵循模型绑定器期望的索引约定。所有字段的格式应该是:
ListProperty[index].PropertyName
在你的例子中,你的JS应该生成这样的名字:
Certifications[0].CertificationName
为了正确的绑定数据
哦不…这是我的错。我给了认证列表作为我的局部视图模型
@model List<SampleApplication.Model.Certification>
但是我也应该在部分视图中使用相同的模型(主页模型)。
@model SampleApp.Models.SampleModel
在局部视图中,编码将像
@for (int i = 0; i < @Model.Certifications.Count; i++)
{
@Html.HiddenFor(m => m.Certifications[i].Id, new { id = "CId" + i.ToString() })
@Html.TextBoxFor(m => m.Certifications[i].CertificationName, new { id = "CName" + i.ToString() })
@Html.TextBoxFor(m => m.Certifications[i].DurationInMonths, new { id = "CDur" + i.ToString() })<br /><br />
}
现在我得到更新的值在我的控制器。
感谢@Chris Pratt的提示