0

So I've looked around StackOverflow a lot and found a nice solution to my problem.

MVC3 DropDownListFor - a simple example?, this ought to do it for me. BUT, it returned a null value... Somehow I have no idea how to go around this so assistance will be appreciated.

Model 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))

I thought maybe my StateID = -1 made it output a null for some reason... but it didn't, you can see it commented out here. What did I do wrong?!

Get Action

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

    return View();
}
Community
  • 1
  • 1
rexdefuror
  • 573
  • 2
  • 13
  • 33

1 Answers1

3

Create an object of your Model/ ViewModel and send that to 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);
}

Now your View should be strongly typed to this Model

So in your Register.cshtml view,

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

}

To Get the Selected State in POST, You can check the State Property value.

[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);
}  
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Ok I've added the object of my model and it worked. But it saves the `StateID` instead of `Value`. How to fix that ? :S – rexdefuror Aug 24 '12 at 11:13
  • @user1407758: Swap the Order of StateID and Value in the Html.DropDownListFor call in your view.( Value should comes first) – Shyju Aug 24 '12 at 11:15