通过AJAX发送类似对象的形式

时间:2015-03-21 21:32:55

标签: jquery ajax json asp.net-mvc model-binding

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

如您所见,我的Ingredients数组包含一个对象,其属性为IngredientOptional。这一切都很好。

当我尝试提交一个与我的表单完全相同的结构的AJAX请求时出现问题。以下是AJAX请求的屏幕截图。

正如您所看到的,Ingredients[index].Ingredient不是Ingredients[index][Ingredient],而是Steps。这破坏了MVC的模型绑定,我无法访问任何属性。 $.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"); } }); 数组仍然可以很好地绑定,即使它缺少索引号。

这是我的AJAX请求:

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和{{1}}。

如果我可以让AJAX请求以与表单相同的方式提交,那么一切都应该正常工作。

2 个答案:

答案 0 :(得分:2)

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

$.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'
  ....

答案 1 :(得分:1)

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

完全有可能在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");
    }
}); 

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