Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the $.ajax to get a partial view

I'm using ASP.NET MVC 3 to build an application, but i'm having a problem when trying to get a partial view; Here's my code

The view :

@{while (Model.Read())
{
    <ul class="tabs">
        <li id="general" class="active">Informations générals</li>
        <li id="contact">Contacts</li>
    </ul>

    <div id="contentDetail">
        <div><b>Description :</b> @Model["Description"]</div>
        <div><b>Activity :</b> @Model["Activity"]</div>
    </div>

    <script type="text/javascript">

        $("#contact").click(function () {
            $.ajax({
                url: '@Url.Content("~/Company/Contacts/")',
                type: 'get',
                data: JSON.stringify('@Model["Id"]'),
                datatype: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    $('#contentDetail').replaceWith(data);
                    },
                error: function (request, status, err) {
                    alert(status);
                    alert(err);
                    }
            });
        });
    </script>
}

}

The controller :

public ActionResult Contacts(int id)
    {
        return PartialView("_Contacts", getContactDetails(id));
    }

"_Contacts" is my partial view, it's strongly typed.

Home I was clear, thanks ^^

like image 817
SidAhmed Avatar asked Jan 17 '12 15:01

SidAhmed


2 Answers

The following is wrong:

data: JSON.stringify('@Model["Id"]')

Replace it with a real JSON object:

data: JSON.stringify(@(Html.Raw(Json.Encode(new { id = Model["Id"] }))))

or with:

data: JSON.stringify({ id: "@Model["Id"]" })

which when rendered in the final markup will look like this:

data: JSON.stringify({ id: "123" })
like image 103
Darin Dimitrov Avatar answered Oct 11 '22 16:10

Darin Dimitrov


You should just be able to return a view not partialview and try this js

var model = { id:"@Model["Id"]" };
 $.post("~/Company/Contacts/,
   model,
   function (data) {
      $('#contentDetail').replaceWith(data);
   });

here is a blog post on it with sample code http://bob-the-janitor.blogspot.com/2011/11/more-ajax-with-mvc-using-partial-views.html

like image 33
Bob The Janitor Avatar answered Oct 11 '22 15:10

Bob The Janitor