代码之家  ›  专栏  ›  技术社区  ›  Frayt

通过AJAX发送类似表单的对象

  •  0
  • Frayt  · 技术社区  · 10 年前

    我有一个网页,允许用户更新他们的食谱。在这个页面上,我为没有javascript的用户提供了一个简单的表单,而我为有javascript的用户则提供了AJAX功能。当我提交表单时,它与我的MVC模型完美绑定,一切都很顺利。以下是表单请求的示例:

    如你所见,我的 Ingredients 数组包含一个对象 Ingredient Optional 这一切都很顺利。

    当我试图提交一个与表单结构完全相同的AJAX请求时,问题就出现了。

    正如你所看到的 Ingredients[index].Ingredient 它是 Ingredients[index][Ingredient] 。这破坏了MVC的模型绑定,我无法访问任何属性。这个 Steps 即使缺少索引编号,数组仍然绑定良好。

    这是我的AJAX请求:

    $.ajax({
            type: "POST",
            url: '/ajax/update_rec',
            contentType: "application/x-www-form-urlencoded",
            data: ajaxrecipe,
            error: function () {
                alert("There was an error updating your recipe, please try again");
            },
            success: function (result) {
                alert("success");
            }
        });
    

    以下是 ajaxrecipe

    var ajaxrecipe =
            {
                RecipeId: $('input#RecipeId').val(),
                RecipeTitle: $('.recipe-information-area > h3.title').val(),
                Ingredients: [],
                Steps: []
            };
    
    ajaxrecipe.Ingredients.push({ Ingredient: ingrediento, Optional: optionalo});
    ajaxrecipe.Steps.push(step);
    

    我一直在网上寻找解决方案,但都没有用。我试过了 JSON.stringify , datatype: "json" , contenttype: "application/json charset utf-8" traditional: true .

    如果我能让AJAX请求以与表单相同的方式提交,那么一切都会正常进行。

    2 回复  |  直到 10 年前
        1
  •  2
  •   user3559349 user3559349    10 年前

    假设您想要发布表单控件,那么您只需要

    $.ajax({
      type: "POST",
      url: '@Url.Action("update_rec", "ajax")', // don't hard code your url's!
      data: $('form').serialize(), // serialize the form
      ....
    

    如果出于某种原因需要使用数组手动构造对象,则需要添加 traditional: true, 并使物体变细

    $.ajax({
      type: "POST",
      url: '@Url.Action("update_rec", "ajax")',
      traditional: true,
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify({ model: ajaxrecipe }), // assumes the method parameter is named 'model'
      ....
    
        2
  •  1
  •   mausworks    10 年前

    您对模型绑定有多熟悉? 我认为问题在于你的模型本身,你忘了发布。

    完全可以在C#中创建模型,然后通过发布的对象(如 JSON ).

    让我举个例子:

    模型:

    public class Recipe 
    {
        public int RecipeId { get; set; }
        public string RecipeTitle { get; set; }
        public List<Ingredient> Ingredients { get; set; }
        public List<string> Steps { get; set; }
    }
    
    public class Ingridient
    {
        public string Ingridient { get; set; }
        public bool Optional { get; set; }
    }
    

    然后可以让控制器接受模型作为第一个参数。

    [HttpPost]
    [ActionName("update_rec")]
    public ActionResult UpdateRecipe(Recipe recipe)
    {
        // do your logic.
    }
    

    然后,您只需确保jQuery代码正确发布它。

    var ajaxrecipe = {
        RecipeId: $('input#RecipeId').val(),
        RecipeTitle: $('.recipe-information-area > h3.title').val(),
        Ingredients: [],
        Steps: []
    };
    
    ajaxrecipe.Ingredients.push({ Ingredient: ingrediento, Optional: optionalo});
    ajaxrecipe.Steps.push(step);
    
    $.ajax({
        type: "POST",
        url: '/ajax/update_rec',
        data: { recipe: JSON.stringify(ajaxrecipe) },
        error: function () {
            alert("There was an error updating your recipe, please try again");
        },
        success: function (result) {
            alert("success");
        }
    }); 
    

    我没有测试过,但以前也做过类似的事情。 请告诉我你的结果!