The task I am trying to accomplish basically involves me using AJAX to call an MVC view, and render the content of the view into my main content div. I understand that as I won't be doing a full page reload, just a refresh on the content I need, I will need to be altering the URL string to account for whichever controller and action I am attempting to call, to get the required view. I havent done a lot of Ajax as of yet, as I am only a junior developer, however I am very interested in learning how to achieve things such as this, and anything that follows.
I am using C# as my primary language, and can use either mvc3 or mvc4, whether or not that makes much difference, I am not sure.
You can use Ajax.ActionLink for this...
@Ajax.ActionLink("Click here", "OtherAction", null, new AjaxOptions() { UpdateTargetId = "MyDiv" })
<div id="MyDiv">
</div>
Action
Public ActionResult OtherAction(long id)
{
return View();
}
View
@{
ViewBag.Title = "Hello!";
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}
<h1>Hello!</h1>
Button:
@supplierQuoteId is from the model via Razor.
<a id="@supplierQuoteId" class="t-button" style="float: right; margin: 3px; padding: 2px; line-height: 0;"
onclick="ajaxEditSupplierQuote(this.id)">
<span class="t-icon t-edit">Edit</span>
</a>
JavaScript:
If $.ajax is complete, I open a Telerik Window and there is a .Content - div with the id="supplierquote-dialog-contet" which is then filled with the returned PartialView from the Controller, otherwise, i set .html(" ") . Empty.
<script type="text/javascript">
function ajaxEditSupplierQuote(id) {
var strUrl = "/SupplierQuote/Edit" + "/" + id.toString();
$.ajax({
type: "GET",
url: strUrl,
dataType: "html",
success: function (data) {
if (!data) {
$('#supplierquote-dialog-content').html(" "); // error check
}
else {
$('#supplierquote-dialog-content').html(data);
}
},
complete: function () {
var window = $("#SupplierQuoteDialog").data("tWindow");
window.center().open();
}
});
}
</script>
SupplierQuoteController:
[HttpGet]
public ActionResult Edit(Guid id)
{
SupplierQuoteEntity supplierQuote = _supplierQuoteRepository.GetById(id);
return PartialView("Edit", supplierQuote);
}
Check out this question, very similar you yours.
ASP.NET MVC - Returning a PartialView to Ajax along with another object
Stealing some code from there you can do something like this:
public ActionResult GetSomePartialView(SomeArgumentModel someArguments)
{
ReturnArgs r = new ReturnArgs();
r.ViewString = this.RenderViewToString("SomeView");
return Json(r);
}
public class ReturnArgs
{
public ReturnArgs()
{
}
public string ViewString { get; set; }
}
Then in view:
$.ajax({
type: "GET",
url: "/Home/GetSomePartialView/",
data: someArguments,
success: function (jsReturnArgs) {
$("#someDiv").html(jsReturnArgs.ViewString); //the HTML I returned from the controller
},
error: function (errorData) { onError(errorData); }
});