开发者

Preselection in a DropDownList

开发者 https://www.devze.com 2023-03-30 04:48 出处:网络
I\'m just starting with MVC3 and I have the following situation. My app\'s initial sign up page among other controls contains a drop down menu. When the user has completed the form then the form deta

I'm just starting with MVC3 and I have the following situation.

My app's initial sign up page among other controls contains a drop down menu. When the user has completed the form then the form details are saved in a session and they move on to the next step. They may also move back to the original step to re-edit, in which case I need to show the drop down menu with the appropriate value preselected.

My code is as follows:

Controller:
public ActionResult Index()
{
   var model = new CompanyDetailsModel();
   BindDropDownLists(model);
   //IF WE HAVE A SESSION THEN PREFILL THE VALUES
   if(MySession.Current.IFA!=null)
   model = EditIFAProfileService.returnCompanyDetailSession(MySession.Current.IFA);
   return View("CreateCompanyDetails", model);
}

I am getting the expected values from the model, so for example the 
value model.Salutation is equal to an integer.

So, armed with that value I would expect to be able to set the preselected value of my dropdownlist as follows:

@Html.DropDownListFor(model => model.SalutationValue, Model.SalutationItems, 
"开发者_JS百科Please Select", new { @tabindex = "1" })

If I do set the model value of SalutationValue to an int then I get an error stating that

ViewData item that has the key is of type 'System.Int32' but must be of type 'IEnumerable'.

Any help would be much appreciated. Thank you.


Don't use any ViewData if you are working with strongly typed views and view models as it would conflict. Simply set the SalutationValue property to some given value. Here's an example:

public ActionResult Index()
{
    var model = new CompanyDetailsModel();
    model.SalutationItems = ...
    if (MySession.Current.IFA != null)
    {
        model.SalutationValue = MySession.Current.IFA;
    }
    return View("CreateCompanyDetails", model);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消