【问题标题】:How to post the viewmodel to action method using JQUERY AJAX in MVC如何在 MVC 中使用 JQUERY AJAX 将视图模型发布到操作方法
【发布时间】:2014-08-03 13:22:51
【问题描述】:

我想使用 $.POST 或 $.AJAX 实现创建(INSERT)屏幕。

注意:代码在没有 AJAX 调用的情况下工作正常。它已经存在了。现在我需要进行 ajax 调用并保存而无需回发。 我写了下面的代码:

关于提交点击事件的代码如下:

$.ajax(
      {
          url: '@Url.Action("CreateProduct","ProductManagement")',
          dataType: 'json',
          contentType: 'application/json; charset=utf-8',
          type: 'post',
          data:   $('frm').serialize(),
          success: function () { alert('s'); },
          error: function (e1, e2, e3) { alert(e2); alert(e1 + ' ' + e2 + ' ' + e3); alert('failure event'); }
      }
    );
});

在服务器端:

[HttpPost]
public JsonResult CreateProduct(FormCollection frm)
{
    manager.ProductManager m = new manager.ProductManager();
    // m.InsertProduct(new common.DTO.ProductDTO() { Id = id, ProductName = ProductName, Description = Description, Cost = cost, ProductTypeId = 5 });
    return Json("'result':'success'", JsonRequestBehavior.AllowGet);
}

问题是,它每次都调用操作,但在 frm 参数参数上找不到数据。 我也试图保持 - 查看模型 ProductViewModel vm 作为参数,但它不起作用..只是给我空值。另外,在ajax调用中,它会成功但是。只是问题是控制器的操作上没有发布任何内容。

HTML如下:

  @using (Html.BeginForm("CreateProduct", "ProductManagement", FormMethod.Post, new { id = "frm" }))
    {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>ProductViewModel</legend>
    <div id="CreateDiv">
        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductName)
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Cost)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Cost)
            @Html.ValidationMessageFor(model => model.Cost)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductTypeId)
        </div>
        <div class="editor-field">
            @Html.DropDownList("ProductTypeId", "Choose item")
            @Html.ValidationMessageFor(model => model.ProductTypeId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductTypeName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductTypeName)
            @Html.ValidationMessageFor(model => model.ProductTypeName)
        </div>
    </div>
    <p>
        <input type="submit" value="Create" id="btnSubmit" />
    </p>

</fieldset>
 }

 <div>
 @Html.ActionLink("Back to List", "Index")
 </div>

请指导我这里出了什么问题。

谢谢

【问题讨论】:

  • 在服务器端代码中您忘记提供名为的属性 - [HTTPPost] 没有 CreateProduct() 方法。
  • 它的 der.. 忘记了 post.apologies。更新了上面的代码。
  • @user3711357...现在获取表单值???

标签: jquery ajax asp.net-mvc-4 asp.net-ajax


【解决方案1】:

对于 id Selector,您必须使用“#”和 id。

这将起作用:

$.ajax(
  {
      url: '@Url.Action("CreateProduct","ProductManagement")',
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      type: 'post',
      data:   $('this').serialize(), OR  $('#frm').serialize(),   <-----------------
      success: function () { alert('s'); },
      error: function (e1, e2, e3) { alert(e2); alert(e1 + ' ' + e2 + ' ' + e3); alert('failure event'); }
  }
 );

或者试试这个:

var form = $('#frm');
$.ajax({
 cache: false,
 async: true,
 dataType: 'json',
 contentType: 'application/json; charset=utf-8',
 type: "POST",
 url: form.attr('action'),
 data: form.serialize(),
 success: function (data) {
 alert(data);
   }
 });

【讨论】:

  • 好的,试过了,但是没有结果……frm.AllKeys.Count() 给了我0 计数值并且没有发布数据。甚至,在我看来,当我做alert($('ProductName').val()); 时,它也给了我未定义的价值。不明白出了什么问题.. 没有 ajax 一切正常。
  • 嘿试试这个警报($('#ProductName').val());你没有使用#
  • 哦,对不起...收到正确值的警报。但是,formcollection 上没有发布任何数据,它只给我计数 0。
  • 现在,当我输入alert($('#frm').serialize) 时,我收到了警报,它显示了序列化数据。现在,这条线data: $('#frm').serialize(), 不起作用..它给了我internal server error 的错误警报,并且无法到达操作方法..
【解决方案2】:

您忘记添加 id 选择器:

$.ajax(
      {
          url: '@Url.Action("CreateProduct","ProductManagement")',
          dataType: 'json',
          contentType: 'application/json; charset=utf-8',
          type: 'post',
          data:   $('#frm').serialize(),                      // $('#frm');
          success: function () { alert('s'); },
          error: function (e1, e2, e3) { alert(e2); alert(e1 + ' ' + e2 + ' ' + e3); alert('failure event'); }
      }
    );

【讨论】:

    【解决方案3】:

    如果你的表单的id是frm,那么应该引用如下

    data:   $("#frm").serialize(),
    

    【讨论】:

    • 当我第一次开始回复你没有放 htlm.正如我所怀疑的那样,上述更改解决问题。
    • 如果您发现您的答案已过时,您可以随时对其进行编辑。这比添加评论来解释为什么您的答案不再与 OP 提供的信息匹配更好。
    • 感谢您的提示。从我的分数你可以看到我刚刚开始。我通常只是阅读答案。我会搞定的。
    • 不客气。我审查了你的第一篇文章。这就是为什么给你这个提示的原因;)你仍然可以通过用 ` 而不是 ' 包装 frm 来改进你的帖子。 'references' 应该是 'referenced' :)
    • 你能告诉我你的意思吗?我无法完全想象这一点。如果将文本添加到代码中,会不会更难阅读?
    猜你喜欢
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多