views:

30

answers:

3

Hello, I'm using asp.net mvc with jquery. I'm trying to make a formpost and just update the ascx that making the post.

I'm making the post with following code:

$(document).ready(function() {
    $('#search-form').submit(function() {
        var form = $('#search-form');
        var action = form.attr('action');
        var serializedForm = form.serialize();

        $.post(action, serializedForm, function() {

        });
        return false;
    });
});

Then I have an action:

[HttpPost]
public ActionResult Method(FormCollection collection)
{
    //code...
    ViewData["post"] = "Hello world";
    return View();
}

This is working fine. The code is executing, but the problems occur after return view. For example if I try to print out the "Hello world" in the view it is never updated. Could someone explain why and do anyone know about a solution?

A: 

When you're making an AJAX request like this, all you have access too in the return is the result returned from the View producted by the action method, not the full data storage associated with the controller.

If you wanted to display the "Hello world" text then you'd have to either write it out to the page as part of your view or include it in the output response.

Response.Write("Hello World");

You don't have access to the ViewData or TempData collections after your view has returned. It sounds like that's what you're expecting.

Jamie Dixon
A: 

Thanks Jamie for your answer.

What I'm trying to do is to show a collection of object as a result in the view. I got the collection in the post action method so I have to let the view got access for it.

"write it out to the page as part of your view " how?

karl
A: 

I suggest that you make ajax.form in a partial view, and do

<div id="DIVtoUpdate"> Render.Partial("PartialViewName",model);</div>

and inside of your partial view u got

using (Ajax.BeginForm("*ActionName*", new { *parameter = ID* }, new AjaxOptions { UpdateTargetId = "DIVtoUpdate", OnSuccess = "*JavaScript that executes on success*",  OnComplete = "s*ame as on success*", InsertionMode = InsertionMode.Replace })) 
{ 
    /*REST OF YOUR VIEW*/ 
}

so when you do post and controller action executes you should return

return PartialView("PartialViewNAme",model);

and your div will get updated with the new data. (note: disable ajax:cache, in some cases you can have problems with it)

Nikola Markezic