【问题标题】:Ajax calls controller action with empty modelAjax 使用空模型调用控制器操作
【发布时间】:2013-12-06 14:45:40
【问题描述】:

单击“更新名称”按钮时,将调用 UpdateDetails 操作,但所有属性的 Customer 模型参数为空。这是为什么呢?

控制器:

public class CustomerController : Controller
{
    public ActionResult Index(int id)
    {
        Customer customer = GetCustomer(id);

        return View(customer);
    }

    [HttpPost]
    public PartialViewResult UpdateDetails(Customer customer)
    {
        UpdateCustomer(customer);

        return PartialView("CustomerUpdateResult", true);
    }
}

查看摘录:

@model MvcTest.Models.Customer

@using (Ajax.BeginForm("UpdateDetails", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "CustomerUpdateResultDiv" }))
{
    @Html.TextBoxFor(cust => cust.Name)
    <input type="submit" value="Update Name" />
}

<div id="CustomerUpdateResultDiv"></div>

【问题讨论】:

  • 检查ModelState.IsValid 标志。如果为 false,则会有一个错误集合告诉您哪里出了问题,您应该将模型返回到视图,以便可以呈现验证消息。
  • 在 chrome/firefox(firebug) 的网络选项卡下检查这个,看看传递的所有 post 参数是什么?
  • 参数为空是什么意思?它是 null 还是 Id 属性可能是 0?
  • 问题中的代码工作正常。可能是您的项目中有其他不在这里的东西给您带来了麻烦。
  • 连名字?或者你的意思是除了名字之外所有的属性都是空的?

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


【解决方案1】:

假设您没有任何其他代码劫持您的点击事件并执行其他操作,上述代码(有问题)应该可以正常工作。

但是您将仅获得 name 属性值,因为您在表单中只有该值。所以所有其他属性都将为空。您可以做的是在表单中包含更多属性或再次读取客户对象并在保存之前仅设置更新的属性值。

@using (Ajax.BeginForm("UpdateDetails", new AjaxOptions { HttpMethod = "POST", 
                                   UpdateTargetId = "CustomerUpdateResultDiv" }))
{
    @Html.TextBoxFor(cust => cust.Name)
    @Html.HiddenFor(c=>c.CustomerID)
    <input type="submit" value="Update Name" />
}

并在 HttpPost 操作中,使用 CustomerID 获取客户对象并更新相关属性值。

[HttpPost]
public PartialViewResult UpdateDetails(Customer customer)
{
    var existingCustomer = GetCustomer(id);
    if(existingCustomer!=null)
    {
      existingCustomer.Name=customer.Name;
      UpdateCustomer(existingCustomer);
      return PartialView("CustomerUpdateResult", true);
    }
    return PartialView("CustomerNotFound", true);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多