altandogan
altandogan

Reputation: 1285

Model object post with ajax in MVC 3

Is it possible to send model object with ajax query in asp.net mvc 3 ? i try this code but it isn't working.

   $.get($(target).data('path')+'list/'[email protected]+'?page='+page+'?searchObject='+@Model, function (data) {
            $(target+' .data-content').unblock();    


            window.setTimeout(function()
            {
                $(target).replaceWith(data);
            },200);

        });
        return false;

I want to send searchParam=@Model

Upvotes: 1

Views: 4875

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Is it possible to send model object with ajax query in asp.net mvc 3

Sure, you could POST it as JSON:

var url = $(target).data('path') + 'list/' + @ModelpagedList.ParentID;
var data = {
    page: page,
    searchObject: @Html.Raw(Json.Encode(Model))
};

$.ajax({
    url: url,
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json',
    success: function(result) {
        $(target + ' .data-content').unblock();    
        window.setTimeout(function() {
            $(target).replaceWith(data);
        }, 200);
    }
});

and your controller action will simply look like this:

[HttpPost]
public ActionResult SomeAction(int parentId, int page, MyViewModel searchObject)
{
    ...
}

But IMHO all this effort is not necessary. No need to waste your bandwidth like that. Just send the identifier of the model that would allow it to retrieve it from your backend - the same way you retrieved it initially when you rendered the view:

[HttpPost]
public ActionResult SomeAction(int id, int parentId, int page)
{
    ...
}

Now you could only send the id of the model and then in your controller action retrieve the corresponding model object using the id. It's only worth sending information from the client to the server that might have been potentially modified by the user. This is not your case. You are just making this model uselessly travel around.

Upvotes: 4

santosh singh
santosh singh

Reputation: 28642

Create an extensions method that convert object to json

public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

and then

   var model = <%= Model.ToJson() %>

$.get($(target).data('path')+'list/'[email protected]+'?page='+page+'?searchObject='+model, function (data) {
            $(target+' .data-content').unblock();    


            window.setTimeout(function()
            {
                $(target).replaceWith(data);
            },200);

        });
        return false;

Upvotes: 1

Related Questions