Bob.
Bob.

Reputation: 4002

How to make JQuery return View?

Before, I had my form directly call the Action, but now, I want to use JQuery to do stuff before having the Action called. The problem I have is that before, when I called return View() from the controller, it would reload the partial page with the message I put into the Viewbag.Message. How do I do that with JQuery?

$("#button").click(function () {
    DoStuff();
});
function DoStuff()
{
    $.ajax("Home/DoStuff"), function() {

    };
}

$

[HttpPost]
public ActionResult DoStuff()
{
    string value = Request.Form["value"];

    Viewbag.Message = TempData["message"];

    CustomView view = new CustomView();
    return View(view);
}

Upvotes: 0

Views: 6469

Answers (1)

David Rettenbacher
David Rettenbacher

Reputation: 5120

Consider something like this (not tested):

<html>
    ...
<body>
    ...
    @Html.RenderAction("DoStuff", new { value: "" });
    ...
</body>

Partial View DoStuff.cshtml:

<div class="doStuffContent">
<script type="text/javascript">
$("#button").click(function () {
    DoStuff();
});
function DoStuff()
{
    $.ajax(
    {
        url: @Url.Action("DoStuff"),
        data: {value: "testData"},
        success: function(result) 
            {
                $("doStuffContent").replaceWith(result);
            }});
}
</script>
<a id="button">click me</a>
@ViewBag.message
</div>

Action:

[HttpGet]
public ActionResult DoStuff()
{
    Viewbag.Message = "";

    return View();
}

[HttpPost]
public ActionResult DoStuff(string value)
{
    Viewbag.Message = "Received " + value + "!";

    return View();
}

Upvotes: 2

Related Questions