视图模型得到的操作方法空​​值 [英] ViewModel getting null values in action method

查看:107
本文介绍了视图模型得到的操作方法空​​值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是视图模型来检索控制器动作输入的数据。但视图模型是它的性能得到空值。我创建有一个局部视图

I am using a ViewModel to retrieve entered data in controller action. But the ViewModel is getting empty values in it's properties. I am creating one partial view

和在局部视图我通过绑定视图模型创建的下拉列表,然后我在其他查看渲染的局部视图>

and in that partial view I am creating drop down lists by binding the ViewModel and then I'm rendering that partial view in other View

下面是我的code

我的视图模型:

public class LookUpViewModel
    {
        RosterManagementEntities rosterManagementContext = new RosterManagementEntities();
        public  LookUpViewModel()
        {

            tblCurrentLocations = from o in rosterManagementContext.tblCurrentLocations select o;
            tblStreams = from o in rosterManagementContext.tblStreams select o;   
        }

        [Required]
        public virtual IEnumerable<tblCurrentLocation> tblCurrentLocations { get; set; }

 [Required]
        public virtual IEnumerable<tblStream> tblStreams {  get;  set; }

我的部分观点:

@model PITCRoster.ViewModel.LookUpViewModel

@Html.Label("Location")
@Html.DropDownListFor(M=>M.tblCurrentLocations, new SelectList(Model.tblCurrentLocations, "LocationId", "Location"), "Select Location")
@Html.ValidationMessageFor(M=>M.tblCurrentLocations)
<br />
@Html.Label("Stream")

@Html.DropDownListFor(M => M.tblStreams, new SelectList(Model.tblStreams, "StreamId", "Stream"), "Select Streams")
@Html.ValidationMessageFor(M => M.tblStreams)

我的视图中,我渲染这段上述局部视图

My View in which I am rendering this above partial view

@{
    ViewBag.Title = "Resources";
}
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<h2>Resources</h2>

@using (Html.BeginForm("AddResource", "Resources", FormMethod.Post))
{

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    Html.RenderPartial("_LookUpDropDowns", new PITCRoster.ViewModel.LookUpViewModel());

    <br />
    <input type="submit" value="Create" />
}

这是我的控制器的操作方法:
[HttpPost]

And this is my controller action method : [HttpPost]

public void AddResource(LookUpViewModel testName)
        {
            //code
        }

当我把一个调试器在我的控制器的操作方法控制进入到操作方法。
但是视图模型对象中有空。
我尝试使用访问输入的值的FormCollection 对象,我让所有的数据如预期...

When I put a debugger on my controller action method control goes to that Action method. But ViewModel object has null in it. I tried accessing entered values using FormCollection object and I'm getting all the data as expected...

下面是我的code与的FormCollection

Below is my code for controller action with FormCollection

 [HttpPost]
        public void AddResource(FormCollection form)
        {
            var x = form["tblStreams"]; //I get value here..
        }

任何人都可以解释我为什么我不能在视图模型对象中获取价值?
谢谢...

Can anybody explain me why I'm not getting values in ViewModel object ? Thank you...

推荐答案

您不能绑定一个DropDownList到复杂对象的集合 - 你的情况的IEnumerable&LT; tblCurrentLocation&GT; 的IEnumerable&LT; tblStream&GT;

You cannot bind a dropdownlist to a collection of complex objects - in your case IEnumerable<tblCurrentLocation> and IEnumerable<tblStream>

A &LT;选择&GT; 标签只回发一个值(所选选项的值),所以在POST方法 DefaultModelBinder 正在尝试让 testName.tblCurrentLocations =1(假设所选选项的值为 1 ),当然这失败,并且属性设置为

A <select> tag only posts back a single value (the value of the selected option) so in the POST method the DefaultModelBinder is attempting to so testName.tblCurrentLocations = "1" (assuming the value of the selected option is 1) which of course fails and the property is set to null

您必须包含要绑定到(理想情况下将包括性能视图模型的的SelectList 所使用的在 DropDownListFor() 助手)

You need a view model containing properties that you want to bind to (and ideally will include the SelectList's used by the DropDownListFor() helper)

public class LookUpViewModel
{
  [Display(Name = "Location")]
  [Required(ErrorMessage = "Please select a location")]
  public int SelectedLocation { get; set; }
  [Display(Name = "Stream")]
  [Required(ErrorMessage = "Please select a stream")]
  public int SelectedStream { get; set; }
  public SelectList LocationList { get; set; }
  public SelectList StreamList { get; set; }
}

然后在视图

@Html.LabelFor(m => m.SelectedLocation)
@Html.DropDownListFor(m => m.SelectedLocation, Model.LocationList, "-Please select-")
@Html.ValidationMessageFor(m => m.SelectedLocation)

@Html.LabelFor(m => m.SelectedStream)
@Html.DropDownListFor(m => m.SelectedStream, Model.StreamList, "-Please select-")
@Html.ValidationMessageFor(m => m.SelectedStream)

和在控制器

public ActionResult Edit()
{
  LookUpViewModel model = new LookUpViewModel();
  ConfigureViewModel(model);
  return View(model);
}

[HttpPost]
public ActionResult Edit(LookUpViewModel model)
{
  if (!ModelState.IsValid)
  {
    ConfigureViewModel(model);
    return View(model);
  }
  // model.SelectedLocation will contain the value of the selected location
  // save and redirect
}

private void ConfigureViewModel(LookUpViewModel model)
{
  // populate your select lists
  var locations = from o in rosterManagementContext.tblCurrentLocations select o;
  model.LocationList = new SelectList(locations, "LocationId", "Location");
  .... // ditto for streams
}

请注意这也如同马克西米利安的回答表明,你的视图模型应该只包含属性您的观点需要。你的控制器负责填充值。视图模型不应该打个电话到一个数据库 - 它甚至不应该知道存在一个

Note as also indicated in Maximilian's answer, your view model should only contain properties your need for the view. Your controller is responsible for populating the values. A view model should never make a call to a database - it should not even be aware that one exists.

这篇关于视图模型得到的操作方法空​​值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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