如何通过AJAX调用将JSON对象和简单字符串传递给控制器​​?

时间:2013-09-11 18:37:31

标签: ajax asp.net-web-api

这是我的路线:

routes.MapHttpRoute(name: "InsertOrUpdateDirector", routeTemplate: "api/awards/directors", defaults: new
    {
       controller = "Awards", action = "InsertDirector"
    });

这是控制器方法:

[HttpPost]
public void InsertOrUpdateDirector(Director director, string operation)
{
   string query = null;

   myConnection.Open();
   if (operation == "I")
   {
     query = "INSERT INTO...";
   }
   else if (operation == "U")
   {
     query = "UPDATE...";
   }
   var cmd = new SqlCommand(query, myConnection);
   cmd.ExecuteNonQuery();
   myConnection.Close();
}

如果我将JSON对象发送到上面,它可以工作。

现在我需要能够传递JSON对象以及字符串参数。

这是仅传递JSON对象的AJAX调用:

$.ajax({
        url: "http://localhost/x/api/awards/directors",
        type: "POST",
        dataType: "json",
        data: directorData 
     }).done(function () {
         detailRow.find(".directorsOrRecipients").data("kendoGrid").refresh();
     });

我的问题是,在这种情况下,如何将JSON对象以及字符串“I”传递给控制器​​?

顺便说一句,

directorData是一个JSON对象。

3 个答案:

答案 0 :(得分:1)

一种快速方法是将其作为查询字符串参数添加到URL:

url: "http://localhost/x/api/awards/directors?operation=I"

或者,如果你有一个变量:

url: "http://localhost/x/api/awards/directors?operation=" + operationValue

另一种选择是将“operation”值添加到JSON对象本身。我不知道你的代码中有Director是什么,但为了论证,让我们说是这样:

{
    "ID" : 1,
    "Name" : "John"
}

然后你可以为该JSON对象添加另一个值:

{
    "ID" : 1,
    "Name" : "John",
    "operation" : "I"
}

这不会混淆服务器端操作方法参数的模型绑定。 JSON对象不需要完全与其中一个模型对齐。模型绑定将尽最大努力根据发布到操作的所有值来确定操作方法参数值。因此,在上面的JSON对象中,它将知道“ID”和“Name”组成一个Director对象,而“operation”是string对象。

答案 1 :(得分:1)

您需要使用director属性和操作属性创建JSON对象。前者包含你的directorData,后者包含你希望传递的字符串。

答案 2 :(得分:0)

您可以调整路线以便它可以处理操作:

routes.MapHttpRoute(name: "InsertOrUpdateDirector",
    routeTemplate: "api/awards/directors/{operation}",
    defaults: new
       {
           controller = "Awards",
           action = "InsertDirector",
           operation = UrlParameter.Optional
       });

然后当你调用它时,请适当地格式化URL:

url: "/Awards/directors/someoper",

这适用于常规MVC(我在这台机器上没有WebAPI,但我希望它也能在那里工作)。

就个人而言,我会避免将operation与常规模型混合使用。它可能会起作用,但以后可能会让人感到困惑。

相关问题