[英]Asp.Net MVC with Drop Down List, and SelectListItem Assistance
[英]How to properly implement a drop-down box using <SelectListItem> and repository pattern in ASP.NET MVC
我想知道如何使用ASP.NET MVC中的<SelectListItem>
類型正確實現下拉框。 我以前沒有使用過這種方法,並且被告知如果必須在下拉菜單中執行“必需”驗證,這是最好的方法。
我以前使用ViewBag創建了一個下拉菜單,但我認為這種方法不太有效。
我的例子很簡單。 一個小型應用程序,允許用戶輸入客戶名稱並從下拉列表中選擇國家。 它還應檢查用戶是否選擇了國家/地區,並在名稱文本框中輸入值。 請在下面查看我的代碼。 它是不完整的,只是一個模板,因此請幫助我如何完全實現此方法。 如果有效,請隨時使用存儲庫。 我仍在努力了解如何使用存儲庫模式,因此也需要對此進行幫助和解釋。 謝謝
客戶視圖模型
public class Customer
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public Country CountryId { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
模型
行動結果
Models.EFEntities ctx = new Models.EFEntities();
public ActionResult GetCustomers()
{
using(ctx)
{
Need code to properly implement this part
}
return view("Customers");
}
[HttpPost]
public ActionResult AddCustomer(Model.Customer customer)
{
using(ctx)
{
//I'm thinking of calling the SaveChanges() method on Customers Entity,
//but please let me know if you have any better ways of writing this code.
// something like using repository pattern)
}
return view();
}
客戶視圖該視圖顯示一個簡單的界面,用於輸入客戶名稱並從下拉菜單中選擇國家/地區。 我在想應該像下面這樣
@model Models.Customer
@Html.EditorFor(model=>model.Name)
@Html.ValidationFor(model=>model.Name)
@Html.DropDownListFor(model => model.Country..?..Need code here as well, "please select")
@Html.ValidationFor(...Need code here to make sure the user selects a country)
在您的Customer
包括選擇列表
public class Customer
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int CountryId { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
像這樣在控制器中構建模型:
public ActionResult GetCustomers()
{
var model = new Customer();
using(ctx)
{
// Need code to properly implement this part
// > I assume you know how to do this, something like:
var customer = ctx.Customers.Get(the_id);
// map the entity to your model
model.Id = customer.Id;
// map the rest of the fields here (you may want to use mapper tools)
// get the country list from your db and map it to selectlistitem
model.Countries = mapCountries(ctx.Countries.GetAll());
}
return view(model);
}
您的看法
@model Models.Customer
@Html.EditorFor(model=>model.Name)
@Html.ValidationFor(model=>model.Name)
// implement the rest of your fields
@Html.DropDownListFor(model => model.CountryId, Model.Countries, "please select")
@Html.ValidationFor(model => model.CountryId)
然后在您的發布方法中
基本上就是這樣,您只需要使用特定於項目的代碼來填充空白即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.