【发布时间】:2012-03-10 13:13:55
【问题描述】:
我有以下控制器和视图。它使用 GET 正确列出了值。当我单击按钮时,它会导致 POST。但是,控制器中接收到的值为 NULL。我们如何纠正它?
高亮代码
[HttpPost]
public ActionResult CastVote(IEnumerable<Program> theProgramList)
获取图片
代码
public enum RatingEnum { Poor = 0, Neutral, Good, Excellent };
public class Program
{
public int ProgramID { get; set; }
public string ProgramName { get; set; }
public RatingEnum RatingID { get; set; }
public string ProgramCategory { get; set; }
}
控制器
namespace MyProgramRatingApp.Controllers
{
public class ProgramController : Controller
{
List<Program> programList = new List<Program>()
{
new Program
{
ProgramID = 1,ProgramName = "Program1",
ProgramCategory = "A"
},
new Program
{
ProgramID = 2,ProgramName = "Program2",
ProgramCategory = "B"
},
new Program
{
ProgramID = 3,ProgramName = "Program3",
ProgramCategory = "A"
}
};
// GET: /Program/
public ActionResult CastVote()
{
ViewBag.RatingEnum = GetRstingSelectList();
return View(programList);
}
// POST: /StoreManager/Create
[HttpPost]
public ActionResult CastVote(IEnumerable<Program> theProgramList)
{
if (ModelState.IsValid)
{
//Save the book in DB first and then redirectToAction.
return RedirectToAction("CastVote");
}
return View(theProgramList);
}
public static SelectList GetRstingSelectList()
{
Array values = Enum.GetValues(typeof(RatingEnum));
List<System.Web.UI.WebControls.ListItem> items = new List<System.Web.UI.WebControls.ListItem>(values.Length);
foreach (var i in values)
{
items.Add(new System.Web.UI.WebControls.ListItem
{
Text = Enum.GetName(typeof(RatingEnum), i),
Value = ((int)i).ToString()
}
);
}
return new SelectList(items);
}
}
}
查看
@model IEnumerable<MyProgramRatingApp.Program>
@{
ViewBag.Title = "CastVote";
}
<h2>CastVote</h2>
@using (Html.BeginForm())
{
<table>
<tr>
<th style="border:1px solid Teal; background-color:Gray">
ProgramName
</th>
<th style="border:1px solid Teal; background-color:Gray">
RatingID
</th>
<th style="border:1px solid Teal; background-color:Gray">
ProgramCategory
</th>
<th style="border:1px solid Teal; background-color:Gray"></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td style="border:1px solid Teal">
@Html.DisplayFor(modelItem => item.ProgramName)
</td>
<td style="border:1px solid Teal">
@Html.DisplayFor(modelItem => item.RatingID)
</td>
<td style="border:1px solid Teal">
@Html.DisplayFor(modelItem => item.ProgramCategory)
</td>
<td style="border:1px solid Teal">
@Html.DropDownListFor(model => item.RatingID, (SelectList)ViewBag.RatingEnum, String.Empty)
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Cast Vote" />
</p>
}
阅读:
ASP.NET MVC 3 - Partial vs Display Template vs Editor Template
用于模型绑定到数组、列表、集合、字典的 ASP.NET 有线格式
模型绑定到列表
【问题讨论】:
-
DisplayFor 可能正在为无法绑定回模型的完整列表生成 ProgramName(在名称 attr 中)。检查 html 中的名称,我认为它们需要是 ProgramName[0]、ProgramName[1] 等。
-
由于我是MVC的新手,我不太明白你的意思。你能提供一个代码演示吗?此外,我的程序数量在实际场景中是动态的(来自数据库)。
-
检查实际发布的值在您的发布操作中接受 FormCollection 参数。
-
我使用FormCollection时,allKeys中只有一个字符串。它是“item.RatingID”