gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:44:33 25 4
gpt4 key购买 nike

我使用 MVC 5 工作了几个月,阅读了大量文章、论坛和文档,但总是想知道 View 中的什么更好;

1) 使用模型的静态方法绑定(bind)数据,如here

2) 使用在 Controller 中设置的 ViewData[index] 绑定(bind)相同的数据,对于前面的示例将如下所示

@Html.DropDownListFor(n => n.MyColorId, ViewData[index])

最佳答案

你想使用方案一,主要是想尽可能使用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"/>

}

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

关于c# - 在 ASP.Net MVC 中使用 DropDownList 的最佳编程实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com