ASP.Net MVC模型绑定IEnumerable失败

时间:2016-06-10 20:01:04

标签: c# asp.net asp.net-mvc-4

我有一个应用程序,它应该在某些文本字段中显示来自本地数据库的对象列表,并可以选择编辑它们。代码在编辑时正确返回列表中的对象,但我的控制器没有看到任何更改。我尝试从Bitmap切换到IEnumerable无效。关于为什么会失败的任何想法(下面的代码)?

型号:

IList

控制器:

public class EmployeeProject
{
    [Required()]
    public Int32 EmployeeProjectID { get; set; }
    [Required()]
    [Range(0, 999999999, ErrorMessage = "Not a valid ID")]
    public Int32 EmployeeID { get; set; }
    [Required()]
    public Int32 ProjectID { get; set; }
    [Display(Name = "Name")]
    public string EmployeeName { get; set; }
    [Display(Name = "Project")]
    public string ProjectName { get; set; }
    [Range(0.0, 1.0, ErrorMessage = "Must be between 0 and 1")]
    public double Hour1 { get; set; }
    ....

    public EmployeeProject()
    {
        EmployeeID = 0;
        ProjectID = 0;
        Hour1 = 0;
        ....
    }
}

查看:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "EmployeeProjectID,EmployeeID,ProjectID,EmployeeName,ProjectName,Hour1,Hour2,Hour3,Hour4")] EmployeeProject employeeProject)
{
    if (ModelState.IsValid)
    {
        db.Entry(employeeProject).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(employeeProject);
}

2 个答案:

答案 0 :(得分:1)

奇怪的是,在你的action方法中,你将返回一个单独的实例 return View(employeeProject);而在您看来,您期待IEnumerable<employeeProject>因为

@model IEnumerable<WebApplication1.Models.EmployeeProject>

你怎么认为这无论如何都会起作用。你的模型应该只是

@model WebApplication1.Models.EmployeeProject

(OR)如果您确实需要,请更改您的操作方法以获取employeeProject

的列表
public ActionResult Edit(List<EmployeeProject> employeeProjects)
{

答案 1 :(得分:0)

以下是我在其中一个项目中的表现

@model List<Game>
@using (Html.BeginForm(FormMethod.Post))
{
 @Html.AntiForgeryToken()
 @for (int i = 0; i < Model.OrderGames.Count(); i++)
 {
 <tr>  
    <td>@Html.EditorFor(m => m.OrderGames[i].GameId})</td>     
    <td>@Html.EditorFor(m => m.OrderGames[i].NumberOfPlayers})</td>
    <td>@Html.EditorFor(m => m.OrderGames[i].GameTime})</td>
    <td>@Html.EditorFor(m => m.OrderGames[i].Price})</td>                                           
</tr>                                    
}
}

您可以在这里翻译成您的项目。 你的控制器应该是这样的

[Httppost]
public ActionResult Edit(List<Game> Games){}