DropdownlistFor会抛出错误

时间:2011-07-15 10:10:09

标签: asp.net-mvc asp.net-mvc-2 asp.net-mvc-3 html.dropdownlistfor

我正在为视图使用下拉列表的硬编码字符串值,并从数据库传递选定的值,其中0 =挂起,1 =完成,3 =等待,下面是视图和控制器的代码:

 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>

它出现了错误: DataBinding:'System.String'不包含名为'Value'的属性。

3 个答案:

答案 0 :(得分:4)

您的示例的问题在于您将字符串数组传递到SelectList,然后告诉SelectList使用ValueText属性(字符串不具有) )。您应该为此创建一个类:

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

更好的是,为这些数据创建一个存储库:

var statusTypes = statusRepository.GetStatusTypes();

将此传递到您的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);

答案 1 :(得分:3)

请使用视图模型:

var paymentStatuses = new[]
{
    new SelectListItem { Value = "0", Text = "Pending" },
    new SelectListItem { Value = "1", Text = "Complete" },
    new SelectListItem { Value = "3", Text = "AwaitingPayment" },
};
var model = new SomeViewModel
{
    StatusID = booking.StatusID,
    Statuses = new SelectList(paymentStatuses, "Value", "Text")
}
return View(model);

然后:

<tr>
    <td>
        Status
    </td>
    <td>
        <%= Html.DropDownListFor(m => m.StatusID, Model.Statuses) %>
    </td>
</tr>

或者你坚持这个ViewData(我不推荐它,特别是你已经有了一个视图模型):

var paymentStatuses = new[]
{
    new SelectListItem { Value = "0", Text = "Pending" },
    new SelectListItem { Value = "1", Text = "Complete" },
    new SelectListItem { Value = "3", Text = "AwaitingPayment" },
};
ViewData["Statuses"] = new SelectList(paymentStatuses, "Value", "Text");
var model = new SomeViewModel
{
    StatusID = booking.StatusID
}
return View(model);

并在视图中:

<tr>
    <td>
        Status
    </td>
    <td>
        <%= Html.DropDownListFor(m => m.StatusID, ViewData["Statuses"] as SelectList) %>
    </td>
</tr>

答案 2 :(得分:1)

错误显示无法找到“值”,您必须执行类似

的操作
new SelectList(paymentStatus, booking.Status, "Text", booking.StatusID)

booking.Status将是预订的任何文本属性。希望这个帮助