我使用以下方法从控制器编辑
编辑了房屋的属性public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
House house = repository.GetHouseById((int)id);
if (house == null)
{
return HttpNotFound();
}
NewHouse newHouse = new NewHouse()
{
House = house,
Types = repository.getAvaiableTypes()
};
return View(newHouse);
}
public ActionResult Edit([Bind(Include = "Id,Description,Type,Price")] House house,string selectedTypeText)
{
ModelState.Clear();
house.Type = selectedTypeText;
if (ModelState.IsValid)
{
try
{
repository.UpdateHouse(house);
repository.SaveChanges();
return RedirectToAction("Index");
}
catch
{
ViewBag.exception = true;
return View(house);
}
}
return View(house);
}
我在ModelView NewHouse中使用类,其结构如下所示
public class NewHouse
{
public House House { get; set; }
public IEnumerable<SelectListItem> Types { get; set; }
public int SelectedTypeId { get; set; }
[Display(Name = "Typ domku")]
public string SelectedTypeText { get; set; }
}
当我保存更改时,对象House和字段selectedTypeText中的所有字段都将传递给POST方法。但我有一个错误
传递到字典中的模型项的类型为&#39; Repository.Models.House&#39;,但此字典需要类型为&#39; Repository.ViewModels.NewHouse的模型项。
我清除ModelState,但它没有帮助。
我应该如何绑定在POST方法中传递对象House和字段selectedTypeText?
在Edit.cshtml中,我使用@model Repository.ViewModels.NewHouse
答案 0 :(得分:0)
正如@Prabhat已经提到的,你需要改变
[Bind(Include = "Id,Description,Type,Price")] House house
到
[Bind(Include = "Id,Description,Type,Price")] NewHouse house
此外,您应该更改视图中输入字段的名称,例如:
<input ... name="Description" ...>
到
<input ... name="House.Description" ...>