贴到模型MVC DropDownList的值不绑定 [英] MVC DropDownList values posted to model aren't bound

查看:217
本文介绍了贴到模型MVC DropDownList的值不绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DropDownLists可能与MVC框架的工作我最不喜欢的部分。我有我的形式,其选定的值我需要传递给接受模型作为其参数一个ActionResult一对夫妇的下拉菜单中

DropDownLists are probably my least favourite part of working with the MVC framework. I have a couple of drop-downs in my form whose selected values I need to pass to an ActionResult that accepts a model as its parameter.

标记看起来是这样的:

The markup looks like this:

<div class="editor-label">
    @Html.LabelFor(model => model.FileType)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.FileType.Variety, (SelectList)ViewBag.FileTypes)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Status)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Status.Status, (SelectList)ViewBag.Status)
</div>

和我控制器操作是这样的:

And my controller action looks like this:

[HttpPost]
public ActionResult Create(int reviewid, ReviewedFile file)
{
    if (ModelState.IsValid)
    {
        UpdateModel(file);
    }

    //repository.Add(file);

    return RedirectToAction("Files", "Reviews", new { reviewid = reviewid, id = file.ReviewedFileId });
}

这应该是一切都很好,除了从下拉菜单中的值是发布为空。当我深入了解一下的ModelState错误,原因是发现是:

This should be all well and good except the values from the drop downs are being posted as null. When I look further into the ModelState errors, the cause is found to be:

这类型
系统参数转换。字符串'键入
'PeerCodeReview.Models.OutcomeStatus'
失败,因为没有类型转换器可以
这些类型之间的转换。

The parameter conversion from type 'System.String' to type 'PeerCodeReview.Models.OutcomeStatus' failed because no type converter can convert between these types.

它不应该这么难,但它是。所以,问题是;我需要做什么才能做到让我的模特属性正确绑定?

It shouldn't be this hard, but it is. So the question is; what do I need to do in order to get my model properties bound correctly?

顺便说一句,我知道我可以在一个的FormCollection对象传递,但是这意味着改变显著。那目前预计强类型的模型参数我的单元测试部分

As an aside, I know I could pass in a FormCollection object, but that means changing significant parts of my unit tests that currently expect a strongly-typed model parameter.

推荐答案

试试这个:

<div class="editor-label">
    @Html.LabelFor(model => model.FileType)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.FileType.Id, (SelectList)ViewBag.FileTypes)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Status)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Status.Id, (SelectList)ViewBag.Status)
</div>

这篇关于贴到模型MVC DropDownList的值不绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆