Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

c# - Best programming practice of using DropDownList in ASP.Net MVC

I'm working with MVC 5 for a few months read a lot of articles, forums and documentation but always wondering what is better in the view;

1) binding data using static method of model like here

2) binding the same data using ViewData[index] which is set in Controller that with previous example will look like this

@Html.DropDownListFor(n => n.MyColorId, ViewData[index])
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to use option 1, mainly because you want to use Strongly Type as much as possible, and fix the error at compile time.

In contrast, ViewData and ViewBag are dynamic, and compile could not catch error until run-time.

Here is the sample code I used in many applications -

Model

public class SampleModel
{
    public string SelectedColorId { get; set; }
    public IList<SelectListItem> AvailableColors { get; set; }

    public SampleModel()
    {
        AvailableColors = new List<SelectListItem>();
    }
}

View

@model DemoMvc.Models.SampleModel
@using (Html.BeginForm("Index", "Home"))
{
    @Html.DropDownListFor(m => m.SelectedColorId, Model.AvailableColors)
    <input type="submit" value="Submit"/>

}

Controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new SampleModel
        {
            AvailableColors = GetColorListItems()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(SampleModel model)
    {
        if (ModelState.IsValid)
        {
            var colorId = model.SelectedColorId;
            return View("Success");
        }
        // If we got this far, something failed, redisplay form
        // ** IMPORTANT : Fill AvailableColors again; otherwise, DropDownList will be blank. **
        model.AvailableColors = GetColorListItems();
        return View(model);
    }

    private IList<SelectListItem> GetColorListItems()
    {
        // This could be from database.
        return new List<SelectListItem>
        {
            new SelectListItem {Text = "Orange", Value = "1"},
            new SelectListItem {Text = "Red", Value = "2"}
        };
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...