How could I set UpdateTargetId on jQuery ajax

13,142

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.

Share:
13,142
Nigiri
Author by

Nigiri

Updated on September 16, 2022

Comments

  • Nigiri
    Nigiri over 1 year

    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" })
    
  • shammelburg
    shammelburg over 9 years
    I specified the URL like: url: "./Controller/Action/{id}"
  • MikeTeeVee
    MikeTeeVee almost 8 years
    This is great! I can now pass in an UpdateTargetID to a Javascript Function for my Checkboxes in MVC. I just had to prefix the UpdateTargetID with a pound-sign like you did here and now when a user checks a box, I can instantly update a list in a separate div container.