使用自定义数据类型发布/提交/保存模型
我创建了一个自定义数据类型(“Days”),并且能够创建一个部分视图“Days.cshtml”,它可以很好地呈现选择列表。
我可以很好地从表单中填充选择列表,但我似乎找不到任何有关如何使用填充的自定义数据类型值发布模型的文档。
public class TimeRequestModel
{
public int EmployeeID { get; set; }
public int JobAllocationID { get; set; }
[DataType("Days")]
public List<SelectListItem> Days { get; set; }
}
Days.cshtml(当我们创建新的“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);
}
在发布模型后,timeRequest.Days 始终为空。
I have created a custom DataType("Days") and have been able to create a partial view "Days.cshtml" which renders a select list just fine.
I am able to populate the select list from the form just fine, but I can't seem to find any documentation as to how to post the Model with the custom DataType values populated.
public class TimeRequestModel
{
public int EmployeeID { get; set; }
public int JobAllocationID { get; set; }
[DataType("Days")]
public List<SelectListItem> Days { get; set; }
}
Days.cshtml (the model will most likely be null as we are creating new "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;" })
My Controller:
[HttpPost]
public ActionResult CreateRequest(TimeRequestModel timeRequest)
{
if (ModelState.IsValid)
{
translator.CreateTimeRequest(timeRequest);
return RedirectToAction("Index");
}
return View(timeRequest);
}
And upon POSTing the Model, timeRequest.Days is always null.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的 ViewModel 中添加一个属性: string DaysSelectedValue
使您的 DropDownList 看起来像这样:
我不太明白为什么您要检查视图中的 Model 是否为 null。据我所知,它永远不应该为空。
In your ViewModel add one more property: string DaysSelectedValue
Make your DropDownList to look like this:
I did not really understand why you are checking if the Model is null in the view. From what I'm seeing, it should never be null.