DropdownlistFor引发错误 [英] DropdownlistFor throws an error
问题描述
我在下拉列表中使用硬编码的字符串值到视图,并从数据库中传递选定的值,其中0 =未决,1 =完成和3 =等待,下面是视图和控制器的代码:
I am using hardcoded string values for dropdownlist to the view , and passing the selected value from database , where 0 = pending , 1 = complete and 3 = awaiting, below is the code for view and controller:
var paymentStatus = new[] { "Pending", "Complete", "AwaitingPayment" };
ViewData["StatusID"] = new SelectList(paymentStatus, "Value", "Text", booking.StatusID);
<tr><td>Status</td><td><%: Html.DropDownListFor(m => m.StatusID, ViewData["StatusID"] as SelectList)%></td></tr>
出现错误: 数据绑定:"System.String"不包含名称为值"的属性.
It comes up with the error : DataBinding: 'System.String' does not contain a property with the name 'Value'.
推荐答案
示例的问题是,您要将字符串数组传递到SelectList
,然后告诉SelectList使用Value
和Text
属性(字符串没有).您可能应该为此创建一个类:
The problem with your example is that you are passing a string array into the SelectList
and then telling the SelectList to use the Value
and Text
properties (which a string does not have). You should probably create a class for this:
public class Status {
public int Id { get; set; }
public string Text { get; set; }
}
var statusTypes = new List<Status> {
new Status { Id = 1, Text = "Pending" },
new Status { Id = 2, Text = "Complete" },
new Status { Id = 3, Text = "AwaitingPayment" }
};
更好的是,为此数据创建一个存储库:
Better yet, create a repository for this data:
var statusTypes = statusRepository.GetStatusTypes();
将此传递到您的SelectList中:
Pass this into your SelectList:
SelectList statusList = new SelectList(statusTypes, "Id", "Text", booking.StatusID);
// return this in a ViewModel or use ViewData like you are now:
ViewData["Status"] = statusList;
return View(statusList);
这篇关于DropdownlistFor引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!