Is there a way to display the CustomerPartial without reloading the page or triggering a postback when a button is clicked? Currently, when I click the button, data is posted to Home/Customer but the browser link always remains as:
localhost:49461
How can I ensure that the browser link displays the following URL after using json post to Home/Customer?
localhost:49461/Home/Customer
I need the browser link to reflect the correct URL instead of always displaying localhost:49461.
What steps should I take in order to change/redirect the browser link using JavaScript and Json?
Here is the HTML code for the button:
<button type="button" onclick="MyFunction">Go To Customer Page</button>
And the corresponding JavaScript function:
function MyFunction() {
$.ajax({
url: "/Home/Customer",
type: "POST",
dataType: "json",
contentType: 'application/json',
success: function (mydata) {
$("#MyDiv").html(mydata);
},
error: function () {
$("#MyDiv").html("Error");
}
});
return false;
}
The Controller method used:
public ActionResult Customer(MyModel model)
{
var stringView = RenderRazorViewToString("CustomerPartial", model);
return Json(stringView, JsonRequestBehavior.AllowGet);
}
Contents of CustomerPartial:
<h1>Welcome To Customer Page</h1>
To handle Json requests:
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}