Nigiri
Nigiri

Reputation: 3629

How could I set UpdateTargetId on jQuery ajax

I want to render the partial view using ajax.
When I submit the button, the partial view must be rendered.
I could implemented it using ActionLink but I want to call the Action by JavaScript.
But the following code doesn't work. The Action is called but the partial view does not be rendered.

View

@section script{
<script type="text/javascript">
    function test() {
        $.ajax(
        {
            type: "POST",
            url: "Test",
            data: "",
            success: function (result) { alert("OK!!"); },
            error: function (req, status, error) {
                alert("Damn!!");}
        });


    }
</script>
}

<input type="submit" onclick="test()" />
<div id="Container">

Controller

public ActionResult Test()
{
    if (Request.IsAjaxRequest())
    {
        return PartialView("ViewUserControl1");
    }
    return View();
}

Partial View ViewUserControl1

Hello world

This works but is not what I want to do

@Ajax.ActionLink("click me", "Test", new AjaxOptions { UpdateTargetId = "Container" })

Upvotes: 4

Views: 13854

Answers (1)

Pavlo
Pavlo

Reputation: 397

Your url may not be correct. It dependent on your routing settings defined in Global.asax . But usually your url should look like "/Home/Test" if your action is in HomeController. It's better to use url helper for getting actions' urls:

...
url: '@Url.Action("Test", "Home")'
...

You can render your partial in next way:

...
success: function (result) { $('#elementId').html(result) },
...

Also if you want to update block, don't forget to clear it first and if it contains form with unobtrusive validation - parse form.

Upvotes: 6

Related Questions