我对 C# 和 MVC 非常陌生,这可能看起来像一个基本问题,但即使在彻底寻找有类似问题的人之后,我也无法让它发挥作用。
问题出在我在编辑视图上的提交按钮上,由于某种原因,该按钮将空数据传递给 Update 方法,而不是表单输入数据。
这是视图:
<div class="row-fluid metro">
<div class="span2 offset4">
@using (Html.BeginForm("Update", "Realty", FormMethod.Post))
{
@Html.HiddenFor(model => model.Address)
@Html.HiddenFor(model => model.Details)
@Html.HiddenFor(model => model.Manager)
@Html.ValidationSummary(true)
<div class="control-group">
<label class="control-label">Details</label>
<div class="controls">
@Html.EditorFor(model => model.Details)
@Html.ValidationMessageFor(model => model.Details)
</div>
</div>
<div class="control-group">
<label class="control-label">Address</label>
<div class="controls">
@Html.EditorFor(model => model.Address)
@Html.ValidationMessageFor(model => model.Address)
</div>
</div>
<div class="control-group">
<label class="control-label">Manager</label>
<div class="controls">
@Html.DropDownListFor(model => model.Manager.Id, Model.Managers)
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Guardar</button>
<a href="@Url.Action("Index", "Realty")"><button type="button" class="btn">Cancelar</button></a>
</div>
}
</div>
这是视图模型 public class RealtyViewModel { /// /// 获取或设置 id。/// public int Id { get; 放; }
public string Address { get; private set; }
/// <summary>
/// Gets the details.
/// </summary>
public string Details { get; private set; }
public List<HomeViewModel> Homes { get; private set; }
/// <summary>
/// Gets the manager.
/// </summary>
public IEnumerable<SelectListItem> Managers { get; set; }
public ManagerViewModel Manager { get; private set; }
public RealtyViewModel(int id,string Address, string Details, ManagerViewModel Manager)
{
this.Id = id;
this.Address = Address;
this.Details = Details;
this.Manager = Manager;
}
public RealtyViewModel() {}
}
}
最后,如果需要,这是来自控制器的 Update 方法:
public ActionResult Update(RealtyViewModel model)
{
if (model.Id == 0)
{
var manager = this.managerService.Get(model.Manager.Id);
this.realtyService.Create(model.Address, model.Details,manager);
}
else
{
var manager = this.managerService.Get(model.Manager.Id);
this.realtyService.Update(model.Id,model.Address, model.Details, manager);
}
return this.RedirectToAction("Index");
}
任何帮助将不胜感激,在此先感谢。
public ActionResult Edit(int id)
{
List<SelectListItem> managers = new List<SelectListItem>();
var model = new RealtyViewModel();
if (id != 0)
{
var realty = this.realtyService.Get(id);
var mvm = new ManagerViewModel(realty.Manager.Id, realty.Manager.Name, realty.Manager.Age);
model = new RealtyViewModel(realty.Id, realty.Address, realty.Details, mvm);
}
foreach (var Manager in managerService.GetAll())
{
managers.Add(new SelectListItem { Value=Manager.Id.ToString(),Text=Manager.Name});
}
model.Managers = managers;
return this.View(model);
}