2

I have been getting into MVC ASP.NET, the potential is very exciting. I have become slightly stuck on a bit and wondered if anyone could give advice, please.

I have worked out how to bundle type object into the viewdata and then access them in a view.

In the view I pick up my viewdata object and assign it to corresponding type.

    @using MyPro.Models;
    @{
      var viewDataMyObj = ViewData["MyObj"] as MyObj;
    }

I then pick it up further down and successfully access my {get,set} and populate a DropDownListFor...

  @Html.DropDownListFor(x => viewDataMyObj.myVar, new      SelectList((IEnumerable<SelectListItem>)viewDataMyObj.mySel.OrderBy(c => c.Value), "Value", "Text", "Select All"), new { @Class = "form-control" })

So, mySel is in my Model and works. It's the string myVar, I can't assign it as an id field. It literally takes "viewDataMyObj.myVar" and puts it as an ID, not the contents of myVar which is "hello". I'm definitely lacking a bit of knowledge at this and would be grateful for any advice.

2 Answers 2

3

Html.DropDownListFor is supposed to work with your Model only. Applying it to viewDataMyObj.myVar won't work. From the code shown, there is no evidence that your view has a model (don't confuse using with model) Assuming that your view supposed to work with MyObj model and that MyObj has myVar property, which is supposed to be filled from drop down this should work:

@model MyPro.Models.MyObj
@{
    var viewDataMyObj = ViewData["MyObj"] as MyObj;
 }

 @Html.DropDownListFor(x => x.myVar, new SelectList((IEnumerable<SelectListItem>)viewDataMyObj.mySel.OrderBy(c => c.Value), "Value", "Text", "Select All"), new { @Class = "form-control" })

You can see that DropDownListFor is for x.myVar which is the property of your model and not for viewDataMyObj.myVar

In addition, if your model is MyObj and it also contains the data to fill your dropdown, you don't need to use ViewData at all:

@Html.DropDownListFor(
    x => x.myVar, 
    Model.mySel.OrderBy(c => c.Value)
      .Select(c => new SelectListItem{Value = c.Value, Text = c.Text}),     
   "Select All", 
   new { @Class = "form-control" })
Sign up to request clarification or add additional context in comments.

2 Comments

You can not use multiple models in the same view. From your comment I assume that you don't understand how MVC works and I suggesst to read about MVC concept in general and about ASP.NET MVC in particular. And one important thing: EVERYTHING THAT CAN BE DONE WITH WEB FORMS COULD BE DONE WITH MVC. MVC is a pattern that allows you to structure your code so it could be more maintainable
Those are not models!!!!. those are just classes. View can have only one model. You need to specify it in view like this @model Namespace.Models.Modelname2
0

Try myVar.Value when creating the ID

Worked for me...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.