我正在尝试在下拉框中包含客户列表。我将此列表包含在一个表单(Html.BeginForm())中,以便我可以将选定的值传递给我的POST控制器。我想我错过了什么,我有以下课程:
my Invoice ViewModel:
public class InvoiceViewModel
{
public InvoiceViewModel()
{
// makes sure InvoiceItems is not null after construction
InvoiceItems = new List<PrelimInvoice>();
}
public List<PrelimInvoice> InvoiceItems { get; set; }
public List<Client> ClientId { get; set; }
public Client Client { get; set; }
public decimal InvoiceTotal { get; set; }
}
我的客户端型号:
public class Client
{
public string ClientId { get; set; }
public string Name { get; set; }
}
我的SaveInvoice方法:
public ActionResult SaveInvoice()
{
var invoice = new Invoice();
TryUpdateModel(invoice);
try
{
invoice.ClientId = User.Identity.Name;
invoice.DateCreated = DateTime.Now;
//Save invoice
proent.Invoices.Add(invoice);
proent.SaveChanges();
//Process the invoice
var preliminvoice = InvoiceLogic.GetInvoice(this.HttpContext);
preliminvoice.CreateInvoice(invoice);
return RedirectToAction("Complete", new { id = invoice.InvoiceId });
}
catch
{
//Invalid - redisplay with errors
return View(invoice);
}
}
我的Index.cshtml强类型为InvoiceViewModel类。 Index.cshtml是我生成表单的地方。
我不确定创建Html.DropDownList的代码,以及我是否需要包含List或我的客户端。我在其他地方有下拉列表,但它们是模型的强类型,而不是视图模型,因此我的困惑。
任何人都可以帮助我吗?
答案 0 :(得分:1)
首先向ViewModel添加以下2个属性:
E.G。
public class ClientViewModel
{
public List<Client> Clients;
public int SelectedClientId { get; set; } // from point 1 above
public IEnumerable<SelectListItem> ClientItems // point 2 above
{
get { return new SelectList(Clients, "Id", "Name");}
}
}
然后在您的View index.cshtml上添加以下内容:
@model ClientViewModel
@Html.DropDownListFor(m => m.SelectedClientId, Model.ClientItems)