user5375600
user5375600

Reputation:

Accessing viewdata object in view

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.

Upvotes: 2

Views: 13261

Answers (2)

Alex Art.
Alex Art.

Reputation: 8781

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" })

Upvotes: 3

jaredlee.exe
jaredlee.exe

Reputation: 81

Try myVar.Value when creating the ID

Worked for me...

Upvotes: 0

Related Questions