0

所以我看了很多 StackOverflow 并找到了一个很好的解决我的问题的方法。

MVC3 DropDownListFor - 一个简单的例子?,这应该为我做。但是,它返回了一个空值......不知何故,我不知道如何解决这个问题,因此将不胜感激。

模型 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; }
...

注册.cshtml

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

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

采取行动

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

    return View();
}
4

1 回答 1

3

创建模型/视图模型的对象并将其发送到视图。

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);
}  
于 2012-08-24T11:08:57.067 回答