模型绑定中的ID为0

时间:2016-04-04 12:31:53

标签: c# asp.net-mvc

我一直在寻找这个问题几个小时试图找到一个我似乎无法找到它的答案。

在我的HttpPost Create操作中,我的ID为0,我无法弄清楚原因。

以下是创建

GET 操作
public ActionResult Create()
    {
        ViewBag.activityID = new SelectList(db.test1, "ID", "text");
        ViewBag.CtyID = new SelectList(db.test2, "ID", "cty");
        ViewBag.AircraftID = new SelectList(db.test3, "ID", "RegNum");
        return View();
    }

Create操作非常基本:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID, /*..more properties*/")] DailySummary dailySummary)
    {

        if (ModelState.IsValid)
        {
            db.DailySummaries.Add(dailySummary);
            db.SaveChanges();
            return RedirectToAction("Index", "/*Controller*/");
        }

        ViewBag.activityID = new SelectList(db.test1, "ID", "text", dailySummary.activityID);
        ViewBag.CtyID = new SelectList(db.test2, "ID", "cty", dailySummary.CtyID);
        ViewBag.ACID = new SelectList(db.test3, "ID", "RegNum", dailySummary.ACID);
        return View(dailySummary);
    }

在我的创建视图中,我有:

@Html.HiddenFor(model=>model.ID)

它仍然被传递为0。

关于为什么没有正确绑定的任何想法?

1 个答案:

答案 0 :(得分:1)

不使用viewbag的最佳方法是为每个下拉列表创建模型,它们可能看起来像......

public class ActivityVM
{
 public int ActivityID {get; set;}
 public string ActivityDesc {get; set;}

}

public class CityVM
{
 public int CityID {get; set;}
 public string CityDesc {get; set;}

}


public class RegVM
{
 public int RegID {get; set;}
 public string RegDesc {get; set;}

}

您的创建视图模型可能看起来像......

public class MyCreateVM
{

  public int ActivityID {get; set;}
  public int CityID {get; set;}
  public int RegID {get; set;}

  public List<ActivityVM> Activities{ get; set; }
  public List<CityVM>  Cities{ get; set; }
  public List<RegVM> Registrations{ get; set; }
  ... etc
}  

,您的创建控制器操作可能如下所示:

public ActionResult Create()
{

  MyCreateVM viewModel = new MyCreateVM();

  viewModel.ActivityList = myActivityService.GetAll();
  viewModel.City = myCityService.GetAll();
  viewModel.RegList  = myRegService.GetAll();

  return View(viewModel);
}

在你看来你会这样做:

<div class="row">
  <div class="col-md-4">
    @Html.DropDownListFor(Model => Model.ActivityID, new SelectList(Model.Activities, "ActivityID, "ActivityDesc"))
  </div>
  <div class="col-md-4">
    @Html.DropDownListFor(Model => Model.CityID, new SelectList(Model.Cities, "CityID, "CityDesc"))
  </div>
  <div class="col-md-4">
    @Html.DropDownListFor(Model => Model.RegID, new SelectList(Model.Registrations, "RegID, "RegDesc"))
  </div>
</div>

然后当它传回你的控制器时,你可以这样做:

[HttpPost]
public ActionResult Create(MyCreateVM viewModel)
{
  if(ModelState.IsValid)
  {
    db.DailySummaries.Add(viewModel)
    db.SaveChanges();
    return RedirectToAction("Index");
  }
  else
  {
    ModelState.AddModelError("", "There was a problem");

    //...some code here to repopulate drop downs

    return View(viewModel);
  }
}