我已經看到了很多這方面的例子,但不能得到任何工作。我已經建立了這個例子來證明/反駁視圖模型SomeDataViewModel的傳回。MVC ViewModel不回發
我想回傳下拉列表數據。一切工作正常,但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
驗證碼:
的ViewModels
TestViewmodel
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);
}
[This](https://stackoverflow.com/questions/26155607/mvc-post-a-list-of-complex-objects)可能會給你方向... –