-1

My question is I already have a model that was created using linq to SQL that I am passing to my view. How do I use this model to populate the select list for the DropDownListFor with cities which is a property in my model. I'm confused about whether I would create a view model to pass to the view for the select list part of my solution when I'm already passing a model created from a linq to SQL class. I have been struggling with how to do this for days. Thanks

JSmith
  • 1
  • 3
  • Suggest you refer [this question/answer](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) for how to code a dropdownlist –  May 27 '16 at 00:05

1 Answers1

0

if you have a model declared in the view like this:

@model Your.Model.Class.Name

You can use public methods and properties from the model in you view:

(if you have the "GetMyCities" public method in your model which returns a list of cities)

<select>
            <%
            foreach (string aSite in Model.GetMySities())
            {                
            %>
                <option  id="<% =aSite%>" value="<% =aSite%>"></option>
            <%
            } 
            %>
            </select>
<select>
Rustam
  • 46
  • 4
  • Thanks for your help. But how do I add this method to my model class if it's generated code. And it says not to alter it? – JSmith May 26 '16 at 14:38
  • You said you have a property with cities list in your model - use that property instead of GetMySities() – Rustam May 26 '16 at 14:46
  • No I don't have a list of cities in my class model that was generated from a table in my domain object. Wasn't aware that's possible. But I will just make a partial method to get the cities and then bind that to my DropDownListFor SelectList. I just hope I don't have any issues when I bind this property to my model parameter. Greatly appreciate your help !!!! – JSmith May 26 '16 at 19:13
  • I understood now, you have an auto generated "data" model when I am talking about "presentation" model. You need to create a "presentation" model (somewhere in your project, usually in the "Models" folder, in that "presentation" model you can create any methods or properties and use your "data" model to get the list of cities. – Rustam May 26 '16 at 20:13
  • And, do not forget to declare that "presentation" model in the controller - @model Your.PresentationModel.Class.Name – Rustam May 26 '16 at 20:20
  • Thanks for the tips – JSmith May 26 '16 at 21:43