Click here to Skip to main content
15,915,869 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI All,
In my project...
I have got an Action Result like this:


C#
public ActionResult GetPartNumber(string Id)
  {
        private readonly PartNumberEntities _Context = new PartNumberEntities();
      var partnumber = _Context.Parts.SingleOrDefault(x => x.ITEMID == Id);
      ViewData["Id"] = Id;



      return PartialView("_PartNumbers", partnumber);

  }


In my view I have this:
C#
@{
   
  

    string partumber = ViewData["id"] as string;
}


            @foreach (var item in Model)
            {
               
            }


I want to loop through all the returned results but as you can see in my view , i am using foreach loop but for some reason it won't let access the properties. for example if i want to look through partnumbers column inside the foreach loop like so:

C#
@foreach(var item in Model){

item.partnumber // here it doesn't even like auto suggest or dropdown option for partnumber.. am i missing anything?? please help?


}
Posted
Comments
Richard Deeming 4-Aug-15 9:58am    
Based on the code you've posted, you're passing a single object to the view, not a collection. What are you expecting the foreach loop to loop over?

You need to tell the view what type your Model is via the @model directive

@model Part

use whatever type you need, I've just guessed it is called Part, as you're using "var" in the controller it's impossible to say. You might need the full namespace as well

@model MyNamespace.Part

Also unless "Part" is also an IEnumerable you won't be able to use a foreach on it.

Accessing the model is quite a basic aspect of MVC, I'd recommend you go through a book or some online tutorials to get an understanding of the basics.
 
Share this answer
 
You can get from ModelMetadata. Refer - Looping through view Model properties in a View[^].
HTML
@foreach(var property in ViewData.ModelMetadata.Properties)
{
    <div class="editor-line">
        <label>@(property.DisplayName??property.PropertyName)</label>
        @Html.Editor(property.PropertyName)
    </div>
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900