我的选择列表的基础来自枚举(在模型中):
public enum week : int
{
Every = 0,
First = 1,
Second = 2,
Third = 3,
Fourth = 4,
Last = 5
}
public enum weekday : int
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
我使用ViewBag将这些发送到View,如下面的函数所示(在控制器中):
private void PopulateDropDown(object selectedLocation = null, )
{
var LocationQuery = from c in db.Location orderby c.name select c;
ViewBag.LocationSelect = new SelectList(LocationQuery, "LocationID", "name", selectedLocation);
var statuses = from week w in Enum.GetValues(typeof(week))
select new { ID = (int)w, Name= w.ToString() };
ViewBag.week = new SelectList(statuses, "ID", "Name");
var weekdayFormat = from weekday s in Enum.GetValues(typeof(weekday))
select new { ID = (int)s, Name = s.ToString() };
ViewBag.weekday = new SelectList(weekdayFormat, "ID", "Name");
}
对于此示例,您可以忽略LocationQuery(即使它不工作......)
我认为:
@Html.DropDownList("locationID", (SelectList)ViewBag.LocationSelect, "Select a location")
和
@Html.DropDownList("Week", (SelectList)ViewBag.TypeSelect, "Week")
@Html.DropDownList("weekday", (SelectList)ViewBag.TypeSelect, "Day")
但是,我发送的数据都不会作为模型的一部分收集:
public class Schedule
{
public Schedule()
{
Times = new List<TimeofDay>();
}
public int ScheduleID { get; set; }
public bool isDisabled { get; set; }
[DisplayName("For Delivery")]
public bool isDeliver { get; set; }
public int Count { get; set; }
public virtual ICollection<TimeofDay> Times { get; set; }
public virtual Location Location { get; set; }
public int Week { get; set; }
public int weekday { get; set; }
}
渲染时,选择列表看起来像我想要的那样:
<select id="Week" name="week"><option value="">Week</option>
<option value="0">Every</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
<option value="5">Last</option>
</select>
但是,我无法获取POST时发送给控制器的值的数据。按照预期,我无法通过schedule.week获得本周的价值。我是否错过了从选择列表中收集的int值的一个步骤,由枚举运算并存储为int?
(感谢阅读)
安德鲁
答案 0 :(得分:0)
我看不到你在哪里设置ViewBag.TypeSelect。
您是否尝试过使用DropDownListFor?
@Html.DropDownListFor(x => x.Week, (SelectList)ViewBag.week, "Week")
修改强>
另外,你的观点肯定是强类型的吗?你能证明这一点吗?
答案 1 :(得分:0)
我认为你的POST动作将Schedule模型作为参数:
[HttpPost]
public ActionResult Foo(Schedule model)
{
...
}
现在让我们先来看看第一个下拉列表:
@Html.DropDownList("locationID", (SelectList)ViewBag.LocationSelect, "Select a location")
提交后,它会在POST请求中将其值发送为locationID=123
。现在看一下Schedule上没有名为LocationID
的属性,所以你没有得到它的价值是完全正常的。您有Location
属性,可能属性为LocationID
。所以你可以像这样修改下拉列表:
@Html.DropDownList("Location.LocationID", (SelectList)ViewBag.LocationSelect, "Select a location")
现在是枚举类型。当我测试时,他们都为我工作。我能够在Week
和weekday
属性中的POST操作中获取与下拉列表中所选值相对应的正确整数值。