【问题标题】:Model is not updated with ajax post in asp.net mvc?模型没有在 asp.net mvc 中使用 ajax post 更新?
【发布时间】:2017-08-04 12:32:26
【问题描述】:

我正在使用 asp.net mvc 应用程序。 在我的视图页面中,我有如下代码的文本框:

@Html.TextBoxFor(m => m.Id, new { @class = "form-control", @readonly = "readonly" })

另外,在表单中提交 ajax 帖子,

$('#btnSubmit').click(function(e)
    {
        $.ajax({
            url: '/button/Button',
            type: 'POST',
            data: {Id:1},
           });
    });

我的控制器:

 MasterM empcode = new MasterM();

        [HttpGet]
        public ActionResult Button()
        {

            var empcode = new MasterM();

            return View(empcode);
         }

        [HttpPost]
        public  ActionResult Button(MasterM model)
        {
            ModelState.Clear();
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            return View(model);
        }

此表单提交后,文本框的值应更改为新值 (1)。我怎样才能在控制器部分本身实现这一点。 我知道在 ajax 成功中我们可以手动更新元素值,但我想在控制器部分实现这一点并使用新值更新模型。

【问题讨论】:

  • 为什么要发送ajax调用,只做普通形式的post
  • 您的模型正在控制器中更新(Id 的值是 1 是 POST 方法)。如果您想更新文本框,请使用 javascript,或者使用您在成功回调中返回的视图更新 DOM
  • 不,我需要 ajax 调用用于其他目的
  • @StephenMuecke,这里的示例我直接给出了 1,但在实际情况下,它会因其他一些操作而改变
  • 如果要返回整个视图,使用 ajax 毫无意义!

标签: c# jquery ajax asp.net-mvc forms


【解决方案1】:

当您发布时,您仅发送单个 ID 而不是整个模型, 所以基本上这个

public  ActionResult Button(MasterM model) will be empty 

并且由于您返回的是空集,因此文本框将不会更新。

您可以在这里做两件事: 1)修改接收类型为

 Public  ActionResult Button(int Id)
    {
    MasterM model = new MasterM();
    model.Id = Id;
     if (!ModelState.IsValid)
                {
                    return View(model);
                }
                return View(model);
    }

2) 如果你想在 Controller 中保留 Model 作为你的 Param 您需要在 Jquery 中序列化数据并发布。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多