且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ASP.Net MVC中使用DropDownList的***编程实践

更新时间:2023-02-16 11:02:51

您想使用选项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"}
        };
    }
}