开发者

AJAX Call using jquery in asp.net mvc

I am making an ajax call using the following code.

$.ajax(  
    {  
        url: '/BuildingCompany/EditAjax/' + id,  
        cache: false,  
        type: 'POST',  
        data: ({ imageValue: $(this).attr("src") }),  
        contentType: 'application/json; charset=utf-8',  
        dataType: 'json'  
}  

In the EditAjax action, how should I retrieve dat开发者_StackOverflow社区a send by this ajax call.


Once the ajax form is submitted, ASP.NET MVC model binder will match the POST parameter "imageValue" to the action method parameter.

Assuming your routes are set up properly, the below should work:

public class HomeController {
    [HttpPost]
    public ActionResult EditAjax(string companyName, string imageValue) {
       //companyName == "BuildingCompany"
       //imageValue == "The Image source"
    }
}

The route setup should look something like this:

routes.Add(new Route("{companyName}/{action}",
    new RouteValueDictionary { { "controller", "Home" } },
    new UIRouting()));


[HttpPost]
public JsonResult EditAjax(string companyName, string imageValue) {
   // do stuff here


   return Json(object);
}


Igor's solution would work if you were using AJAX to send a form normally but you are sending JSON so an extra step is needed.

In the MVC futures library (available on CodePlex) is a JSONValueProvider. Download the library and reference Microsoft.Web.Mvc.

In your Global.asax.cs Application_Start() method add the line:

ValueProviderFactories.Factories.Add(new Microsoft.Web.Mvc.JsonValueProviderFactory());

This will let your action methods model bind against JSON as you would normally. You might already know this but as you are using JSON you can return

Json(object)

Which will serialise your object to JSON, send correct content-type etc for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜