[英]MVC ViewModel not posting back
我已经看到了很多例子,但是没有任何效果。 我建立了这个示例,以证明/不赞成将视图模型SomeDataViewModel传回。
我正在尝试回发下拉列表数据。 一切正常,但是TestViewModel的OtherData属性从不返回传入的收集。
尝试添加:
@Html.HiddenFor(m => Model.OtherData)
但这又会产生以下错误;
The parameter conversion from type 'System.String' to type 'SomeDataViewModel' failed because no type converter can convert between these types
编码:
视图模型
测试视图模型
public class TestViewModel
{
public TestViewModel()
{
OtherData = new List<SomeDataViewModel>();
}
public int Id { get; set; }
public String Name { get; set; }
public DateTime DoB { get; set; }
public int SelectedOtherData { get; set; }
public List<SomeDataViewModel> OtherData { get; set; }
public IEnumerable<SelectListItem> TolistData()
{
IEnumerable<SelectListItem> ret = OtherData.Select(i => new SelectListItem() { Text = i.Text, Value=i.Value });
return ret;
}
}
SomeDataViewmodel
public class SomeDataViewModel
{
public string Value { get; set; }
public string Text { get; set; }
}
视图
@model TestViewModel
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm("Index","Home"))
{
<div class="row">
<div class="col-md-12">
<br />
@Html.EditorFor(m => Model.Id)
<br />
@Html.EditorFor(m => Model.Name)
<br />
@Html.EditorFor(m => Model.DoB)
<br/>
@Html.DropDownListFor(m => Model.SelectedOtherData, Model.TolistData(), new { id = "OtherData" })
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
</div>
<button id="dosomething" formmethod="post">Post</button>
}
控制者
public ActionResult Index()
{
var model = new TestViewModel() {
Id = 99,
Name = "Billy",
DoB = DateTime.Now
};
model.OtherData.Add(
new SomeDataViewModel { Text = "Bob", Value = "1" });
model.OtherData.Add(
new SomeDataViewModel { Text = "Sally", Value = "2" });
return View(model);
}
[HttpPost]
public ActionResult Index(TestViewModel retModel)
{
if (ModelState.IsValid)
{
if (retModel.OtherData.Count() == 0)
{
var dud = true;
}
}
return View(retModel);
}
您无法使用@Html.HiddenFor
helper渲染复杂数据的隐藏输入。
您应该仅将其与简单类型一起使用。 因为有了数组,您应该编写如下代码:
@for(int i = 0; i < Model.OtherData.Count(); i++)
{
@Html.HiddenFor(m => Model.OtherData[i].Text)
@Html.HiddenFor(m => Model.OtherData[i].Value)
//... other fields.
@Html.HiddenFor(m => Model.OtherData[i].OtherProperty)
}
使用for
循环而不是foreach
您应该对表单POST
上的绑定进行相同的映射。
当然存在类型转换错误。 您的SelectedOtherData是int类型,而selectlistitem值是字符串类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.