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 ^^
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" })
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With