栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您要使用选项1,主要是因为要尽可能使用 Strongly Type ,并在编译时修复错误。

相反, ViewDataViewBag 是动态的,并且在运行时,编译无法捕获错误。

这是我在许多应用程序中使用的示例代码-

模型

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576100.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号