我的视图模型是:
public class CompanyAccountViewModel
{
public string Name { get; set; }
public float Interval { get; set; }
public List<string> MobileNo { get; set; }
}
我的观点是:
@model PowerSupply.Models.CompanyAccountViewModel
@{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Register</h3> <br />
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group row">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "col-sm-2 col-md-1 col-form-label" })
<div class="col-sm-10 col-md-3">
@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 row">
@Html.LabelFor(model => model.Interval, htmlAttributes: new { @class = "col-sm-2 col-md-1 col-form-label" })
<div class="col-sm-10 col-md-3 positioned_relative">
@Html.EditorFor(model => model.Interval, new { htmlAttributes = new { @class = "form-control" } })
<span class="help-text">Hour</span>
@Html.ValidationMessageFor(model => model.Interval, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group row">
@Html.LabelFor(model => model.MobileNo, htmlAttributes: new { @class = "col-sm-2 col-md-1 col-form-label" })
<div class="col-sm-10 col-md-3">
<span class="add-new-icon glyphicon glyphicon-plus-sign" id="add_mobile"> </span>
@Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { @class = "form-control",@id= "add_mobile" } })
@Html.ValidationMessageFor(model => model.MobileNo, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group row new_mobile_wrapper">
<div class="col-md-offset-3">
<div class="new_mobile_container">
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-offset-2 col-sm-10 col-md-2">
<input type="submit" value="Register" class="btn btn-primary col-sm-offset-1" />
</div>
</div>
}
在这里,我的所有字段都已正确呈现,但是:
@Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { @class = "form-control",@id= "add_mobile" } })
这不会生成任何标记。我指出原因,这是由于实体类型。"移动编号"的实体类型为"列表"。如何修改此@Html.EditorFor
?知道吗?它杀死了我一整天。
问题出在此属性上:
public List<string> MobileNo { get; set; }
由于用户可能有多个移动电话号码,因此无法将此集合绑定到单个@Html.EditorFor()
帮助程序(与当前状态一样绑定不会生成任何 HTML 标记(。您需要使用循环为每个string
值生成EditorFor
帮助程序:
@for (var i = 0; i < Model.MobileNo.Count; i++)
{
@Html.EditorFor(m => m.MobileNo[i], new { htmlAttributes = new { @class = "col-sm-2 col-md-1 col-form-label" } })
}
或者使用TextBoxFor
作为替代方案,也在循环内:
@for (var i = 0; i < Model.MobileNo.Count; i++)
{
@Html.TextBoxFor(m => m.MobileNo[i], new { @class = "col-sm-2 col-md-1 col-form-label" })
}
如果要从媒体资源动态创建手机号码输入List<string>
请参阅此文章以开始使用。
这可能是因为当您的 MobileNo 列表在 CompanyAccountViewModel 返回到视图时没有数据值。