使用自定义DataType POST / Submit / Save a Model

时间:2011-10-11 17:29:19

标签: asp.net-mvc data-manipulation metadatatype

我创建了一个自定义DataType(“Days”),并且能够创建一个部分视图“Days.cshtml”,它可以很好地呈现选择列表。

我能够很好地填充表单中的选择列表,但我似乎找不到任何关于如何使用填充的自定义DataType值发布模型的文档。

public class TimeRequestModel
{
    public int EmployeeID { get; set; }
    public int JobAllocationID { get; set; }
    [DataType("Days")]
    public List<SelectListItem> Days { get; set; }
}

Days.cshtml(模型很可能是null,因为我们正在创建新的“Days”)

@model TimeRequestModel
@Html.DropDownList("", (Model != null ? Model.Days : new List<SelectListItem>()), new { @class = "customfield", @type = "custom", @multiple = "multiple", @size = "14", @style = "text-align: center; float: right; width: 225px;" })

我的控制器:

[HttpPost]
    public ActionResult CreateRequest(TimeRequestModel timeRequest)
    {
        if (ModelState.IsValid)
        {
            translator.CreateTimeRequest(timeRequest);
            return RedirectToAction("Index");
        }

        return View(timeRequest);
    }

在POST模型时,timeRequest.Days始终为null。

1 个答案:

答案 0 :(得分:0)

在ViewModel中添加一个属性:string DaysSelectedValue

让你的DropDownList看起来像这样:

@Html.DropDownList(model => model.DaysSelectedValue, Model.Days, new { @class = "customfield", @type = "custom", @multiple = "multiple", @size = "14", @style = "text-align: center; float: right; width: 225px;" })

我真的不明白你为什么要检查视图中的Model是否为null。从我所看到的,它永远不应该是空的。