MVC 3 DropDownFor和视图模型不能正常工作 [英] MVC 3 DropDownFor and ViewModel not working

查看:94
本文介绍了MVC 3 DropDownFor和视图模型不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2型号:

public class Person
{
    public Guid ID { get; set; }
    public string Name { get; set;}
}

public class Event
{
    public Guid ID { get; set; }
    public string EventName { get; set; }
    public virtual Person Owner { get; set; }
}

我有一个视图模型:

I have a ViewModel:

public class EventViewModel
{
     public EventViewModel() { }
     public Event EventToEdit { get; set; }
     public SelectList People { get; set; }
}

我有我的控制器:

I have my Controller:

public ViewResult Create()
{
     var eve = new Event();
     var vm = new EventViewModel
                 {
                     EventToEdit = eve,
                     People = GetPeopleList(true, eve)
                 }
     return View(vm)
 }

我有我的观点:

@Html.DropDownListFor(x => x.EventToEdit.Owner, Model.People)

显然,他们都砍了阅读的目的。

Obviously they are cut down for reading purposes.

当我提出我的看法,并创下一个断点的ActionResult创建

When I submit my view, and hit a breakpoint in the ActionResult Create


  1. 它不具备对所有者(列表中正确填充)的值

  2. 视图模型的人也为空

使用视图模型的要点是传递信息,并从该视图控制器所以,首先,为什么人们空。

The point of using a ViewModel is carry information to and from the view to the controller so firstly why is People null.

其次,最重要的是,为什么地球上是业主没有得到正确填充。还有人选择。事件名称将通过模型,视图模型是工作有点被传递回...

Secondly and most importantly, why on earth is Owner not getting populated properly. There are people to choose from. Event name will be passed back through the model so the ViewModel is working somewhat...

谢谢,

推荐答案

考虑karaxuna的回答是:

Taking karaxuna's answer:

首先,它应该是:

@ Html.DropDownListFor(X => x.EventToEdit.Owner.ID,Model.People)

所以这Model.People是这样的:

So that Model.People was something like this:

新的SelectList(源,ID,姓名,source.ID)

和扩大是:

新的视图模型:

public class EventViewModel
{
    public EventViewModel() { }
    public Event EventToEdit { get; set; }
    public SelectList People { get; set; }
    public Guid SelectedPerson { get; set; }
}

查看绑定:

@Html.DropDownListFor(x => x.SelectedPerson, Model.People)

然后在控制器:

var person = _repository.People.FirstOrDefault(x => x.ID.CompareTo(vm.SelectedPerson) == 0);
vm.EventToEdit.Person = person;
_repository.SaveEvent(vm.EventToEdit);

我写这个答案清晰,谁自带搜索的威力preFER看到一个完整的页面。

I write this answer for clarity, anyone who comes searching might prefer to see a complete page.

这篇关于MVC 3 DropDownFor和视图模型不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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