DropDownListFor null值,使用引用

时间:2012-08-24 10:51:07

标签: c# asp.net-mvc razor

所以我仔细研究了StackOverflow并找到了解决问题的好方法。

MVC3 DropDownListFor - a simple example?,这应该为我做。但是,它返回了一个空值...不知怎的,我不知道如何解决这个问题,所以将不胜感激。

模型AccountModel.cs

...
public string Address { get; set; }
public string City { get; set; }

public class StateList
{
    public int StateID { get; set; }
    public string Value { get; set; }
}

public IEnumerable<StateList> StateListOptions = new List<StateList>
{
    //new StateList { StateID = -1, Value = "Select State" },
    new StateList { StateID = 0, Value = "NY" },
    new StateList { StateID = 1, Value = "PO" }
};

public string State { get; set; }

public string Zip { get; set; }
...

Register.cshtml

@Html.DropDownListFor(m => m.State, new SelectList(Model.StateListOptions, "StateID", "Value", Model.StateListOptions.First().StateID))

我想也许我的StateID = -1由于某种原因输出了一个null ...但它没有,你可以看到它在这里注释掉了。我做错了什么?!

获取行动

public ActionResult Register()
{
    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

    return View();
}

1 个答案:

答案 0 :(得分:3)

创建Model / ViewModel的对象并将其发送给view。

public ActionResult Register()
{    
    AccountModel vm=new AccountModel();

    //Not sure Why you use ViewData here.Better make it as a property
    // of your AccountModel class and pass it.
    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

    return View(vm);
}

现在您的视图应该强烈输入此模型

所以在Register.cshtml视图中,

@model AccountModel
@using(Html.BeginForm())
{
   //Other form elements also
   @Html.DropDownListFor(m => m.State, new SelectList(Model.StateListOptions, 
                                                "StateID", "Value")"Select")
   <input type="submit" />

}

要在POST中获取选定状态,您可以检查State属性值。

[HttpPost]
public ActionResult Register(AccountModel model)
{
   if(ModelState.IsValid)
   {
      // Check for Model.State property value here for selected state   
      // Save and Redirect (PRG Pattern)
   }
   return View(model);
}