MVC ViewModel没有发回

时间:2017-05-26 11:17:26

标签: c# asp.net-mvc asp.net-mvc-4

我已经看过很多这方面的例子,但是无法正常工作。我已经构建了这个例子来证明/反驳视图模型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

守则:

的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 &raquo;</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);
    }

2 个答案:

答案 0 :(得分:2)

您无法使用@Html.HiddenFor帮助程序为复杂数据呈现隐藏的输入。

您只能将它用于简单类型。如果你有阵列你应该写这样的东西:

@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格式上设置正确绑定的映射。

答案 1 :(得分:0)

当然存在类型转换错误。您的SelectedOtherData是int类型,而selectlistitem值是字符串

的类型