roncansan
roncansan

Reputation: 2380

How to pass data to the view in mvc asp.net?

let me ask the question first.

Where is the correct place to call a function that load a list of values to be display on a view?

I create a controller like this

public ActionResult Create()
{
    SeaModel newSea = new SeaModel();

    return View("Season/CreateSea", newSea);
}

//I not quite sure if this should go here or in another place
partial class seaDataContext
{
    public List<string> getSeaSettings()
    {
        var seaSettings = from p in settings
                          where p.setting == "periods"
                          select p.value;

        return seaSettings.ToList<string>();                              
    }
}

The model is like

public class SeaModel
{
    [Required(ErrorMessage="*")]
    [Display(Name = "Period Name")]
    public string periods { get; set; }    
}

Which create a view like

  @using (Html.BeginForm()) {
        @Html.ValidationSummary(true, "Please correct the following errors.")

        <fieldset>
            <legend>Fields</legend>

            <div class="editor-label">
                @Html.LabelFor(model => model.periods)
            </div>
            <div class="editor-field">
                @Html.Select(model => model.periods, ****My doubt comes here****)
                @Html.ValidationMessageFor(model => model.periods)
            </div>

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    }

so, How and where do I pass the return of getSeaSettings() to the view?

Thanks

Upvotes: 2

Views: 4071

Answers (3)

stun
stun

Reputation: 1744

Stefanvds's approach was what I used to do.
But I found out there is a better way using additionalViewData.

Use this EditorFor HTML Helper extension method.
http://msdn.microsoft.com/en-us/library/ff406462.aspx

Instead of passing Select List Items into ViewData in the Controller, you do this in your View.

Pass in your list items as an anonymous object for the additionalViewData parameter.
Important thing is to use the same name as your Property Name.

@Html.EditorFor(
    m => m.MyPropertyName,
    new { MyPropertyName = Model.ListItemsForMyPropertyName }
);


Of course, you are passing in a View Model object.

public class MyViewModel
{
    public int MyPropertyName;

    public IList<SelectListItem> ListItemsForMyPropertyName;
}



EditorFor method uses your existing Editor View Templates.
So you don't need to specify CSS class names and HTML attributes again like when you use the Html.DropDown( ) method.

For example,

//------------------------------
// additionalViewData
//------------------------------
@Html.EditorFor(
    m => m.MyPropertyName,
    new { MyPropertyName = Model.ListItemsForMyPropertyName }
)

//------------------------------
//  traditional approach requires to pass your own HTML attributes
//------------------------------
@Html.DropDown(
    "MyPropertyName",
    Model.ListItemsForMyPropertyName,
    new Dictionary<string, object> {
        { "class", "myDropDownCssClass" }
    }
);

//------------------------------
//  DropDownListFor still requires you to pass in your own HTML attributes
//------------------------------
@Html.DropDownListFor(
    m => m.MyPropertyName,
    Model.ListItemsForMyPropertyName,
    new Dictionary<string, object> {
        { "class", "myDropDownCssClass" }
    }
);

That is why I like the additionalViewData approach more.
Because, the HTML code rendered relies on the Editor Templates completely.

Also, using specialized View Models make your code cleaner and easier to maintain.

Hope it helps.

Upvotes: 2

Tassadaque
Tassadaque

Reputation: 8199

You need to look at repository pattern. Have a look at this tutorial at asp.net site http://www.asp.net/mvc/tutorials/creating-model-classes-with-linq-to-sql-cs

Upvotes: 2

Stefanvds
Stefanvds

Reputation: 5916

best practice is to make a Selectlist in your Model for this dropdown.

however you also can use the more easy option: using ViewData

 public ActionResult Create()
 {
     SeaModel newSea = new SeaModel();

     ViewData["myDropDown"] = new SelectList(listOfObjects, "valueOfTheObjectLikeID", "NameYouWantToShowInDropdown");

     return View("Season/CreateSea", newSea);
 }

then:

@Html.Select(model => model.periods, ViewData["myDropDown"] as SelectList)

dont forget in your [HttpPost] method to also fill in the viewdata if you'r validation fails, so the dropdown can be rebuilt.

Upvotes: 4

Related Questions