Asp.net mvc 无法在ActionResult中检索ViewModel
我使用MVC 3,我有一个带有以下代码的控制器,我无法获取ViewModel[HttpPost]ActionResult删除AdvSlotDeleteViewModel结果NULL,我有一个类似的编辑操作方法,它正在工作,你能帮我解决这个问题吗Asp.net mvc 无法在ActionResult中检索ViewModel,asp.net-mvc,asp.net-mvc-3,Asp.net Mvc,Asp.net Mvc 3,我使用MVC 3,我有一个带有以下代码的控制器,我无法获取ViewModel[HttpPost]ActionResult删除AdvSlotDeleteViewModel结果NULL,我有一个类似的编辑操作方法,它正在工作,你能帮我解决这个问题吗 // GET: /ManageAdvSlots/Delete/5 public ActionResult Delete(int id) { AdvSlot advSlot = advSlotRepository.Find
// GET: /ManageAdvSlots/Delete/5
public ActionResult Delete(int id)
{
AdvSlot advSlot = advSlotRepository.FindById(id);
AdvSlotDeleteViewModel deleteViewModel = Mapper.Map<AdvSlot, AdvSlotDeleteViewModel>(advSlot);
return View(deleteViewModel);
}
//
// POST: /ManageAdvSlots/Delete/5
[HttpPost]
public ActionResult Delete(AdvSlotDeleteViewModel deleteViewModel)
{
if (ModelState.IsValid)
{
AdvSlot advSlot = Mapper.Map<AdvSlotDeleteViewModel, AdvSlot>(deleteViewModel);
advSlotRepository.Delete(advSlot.AdvSlotId);
advSlotRepository.Save();
}
return RedirectToAction("Index");
}
}
您需要将所有表单字段放在表单块中。否则它们将不会发布到服务器
使用(Html.BeginForm()){->>将您的
移动到@内部这里人们建议只在隐藏的表单字段中包含id即可:
@using (Html.BeginForm()) {
@Html.HiddenFor(x => x.AdvSlotId)
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}
@使用(Html.BeginForm()){
@Html.HiddenFor(x=>x.AdvSlotId)
|
@ActionLink(“返回列表”、“索引”)
}
您可能会发现不想再检查模型是否有效。如果您对某些字段进行了高级验证,如果这些字段不在表单中,则不会发回。例如,如果“Name”是必需的,上面的代码验证将失败,因为只有表单中的字段被发回服务器。您也可以发布您的Cshtml吗?我发布了Cshtml和ViewModel,我希望可以帮助您,感谢您花时间在这方面!+1当我看到问题刷新时正在键入此内容-太快:)谢谢Jakub,对不起,您能告诉我吗找出错误的确切位置,我无法理解它,我在MVC非常nw感谢感谢感谢Steve它工作得很好,我忘记了隐藏字段,现在工作得很好谢谢!是的,我可以在ViewModel上删除验证逻辑,因此我使用if(ModelState.IsValid)…谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyProject.ViewModels
{
public class AdvSlotDeleteViewModel
{
public int AdvSlotId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsPublished { get; set; }
public string Code { get; set; }
public string Note { get; set; }
}
}
@using (Html.BeginForm()) {
@Html.HiddenFor(x => x.AdvSlotId)
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}