2

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

1
  • sea.. periods... Red Sea for sure! Commented May 20, 2011 at 7:43

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This gives me the following errorCompiler Error Message: CS1501: No overload for method 'Select' takes 2 arguments Source Error: Line 53: @Html.Select(model => model.periods,ViewData["sl"] as SelectList)
use SelectFor? i'm dont know much about MVC3 :) also you can input a string which would show by default like "Select your period..."
in MVC2 that looks like this: <%: Html.DropDownListFor(model => model.someID, ViewData["someList"] as SelectList,"Select a thing...")%>
MVC3 also has Html.DropDownListFor()
2

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

2 Comments

I agree with using the repository pattern. It's how I've done such things in the past and keeps things nicely separated.
you may skip (if you opt) interfaces and may create concrete repository classes directly
2

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.