在ASP.Net MVC中使用DropDownList的最佳编程实践 [英] Best programming practice of using DropDownList in ASP.Net MVC

查看:53
本文介绍了在ASP.Net MVC中使用DropDownList的最佳编程实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与MVC 5一起工作了几个月,阅读了许多文章,论坛和文档,但总是想知道哪种方法更好?

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)使用静态模型(如此处)绑定数据

1) binding data using static method of model like here

2)使用在Controller中设置的ViewData [index]绑定相同的数据,与上一个示例类似

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])

推荐答案

您想使用选项1,主要是因为您想尽可能多地使用 Strongly Type 并修复编译时的错误时间.

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.

相反, ViewData ViewBag 是动态的,并且编译必须在运行时才能捕获错误.

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 -

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

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

查看

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

}

控制器

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"}
        };
    }
}

这篇关于在ASP.Net MVC中使用DropDownList的最佳编程实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆