Rendering Partial Views using ajax - c#

I've checked this question and it solved my initial problems. But I don't want the partial view to be rendered only when the user clicks a link, I want to render partial views when the page is loaded and, possibly, show a progress indicator while the partial view is being loaded.
How to achieve that?
Thank you very much for reading this.

If you want to load the page and then load the partial view via ajax you could create an ActionMethod that does something like:
public ActionResult Create()
{
var model = new MyModel();
if (Request.IsAjaxRequest())
{
return PartialView( "_Partial", model.PartialModel );
}
else
{
return View( model );
}
}
and then in your page do something like:
$(function(){
$(document).ajaxStart(function () {
//show a progress modal of your choosing
showProgressModal('loading');
});
$(document).ajaxStop(function () {
//hide it
hideProgressModal();
});
$.ajax({
url: '/controller/create',
dataType: 'html',
success: function(data) {
$('#myPartialContainer').html(data);
}
});
});

Controller
public ActionResult GetModule(string partialName){
return PartialView("~/Views/Shared/"+partialName);
}
on the Default Page (using jquery ajax operation)
<div id='mod1'>Loading...</div>
<script type="text/javascript">
$("#mod1").load("/ControllerName/GetModule?partialName=test1");
</script>

You can render it in the initial page by writing #Html.Partial(...).

Related

How to get the error message during a jquery post while using aps.net mvc?

I'm using 2019 ASP.NET MVC with jquery 3.4.1. I'm trying to get the error message when I make a jquery ajax post. To simulate an error I mispelled the method in the controller being called by ajax. The best I could do was to display an alert box with some HTML code. It looks like the title tag contains the correct error message: "The resource cannot be found." But it's nested inside of a bunch of html code.
Is there a way to get that error message out of that html code and into a string?
Edit: I figured it out. I just added a span tag and set the html property of it.
Controller
using System.Web.Mvc;
namespace Test
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
//view
return View();
}
[HttpPost]
public ActionResult DoSomething1111111111()
{
return Json("hello");
}
}
}
View
#{
Layout = null;
}
<input type="button" id="test-button" value="test" />
<span id="message"></span>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script>
//test-button click event
$(document).on("click", "#test-button", function () {
//post
$.ajax({
url: "/Home/DoSomething",
type: "POST",
success: function (res) {
alert("success");
},
error: function (res) {
$("#message").html(res.responseText);
}
});
});
</script>

cshtml view not rendering

I am using ASP.net MVC with the razor engine.
I have a page with a button, when the button is clicked i call an ActionResult in my controller using Ajax. The Ajax call:
$.ajax({
type: "GET",
url: "/Home/Review",
success: function (data) {
//alert("yay");
}
});
My ActionResult method is hit fine, however it does not load the view speified.
The code:
public ActionResult Review()
{
return View();
}
The current view is Index.cshtml when Review() is hit i would like Review.cshtml to be rendered on screen. (It should be rendered as a full view, not as partial view inside Index.cshtml)
I have tried - return View("Review"); return View("Review.cshtml"); return View("..\Views\Home\Review.cshtml);
I can't use - tml.BeginForm("Action", "Controller", FormMethod.Post); (see my other question MVC submit button not firing)
Write the response directly to the screen
success: function (data) {
document.write(data) }
After ajax, you should render a partial view to add returning result to main view(index).
Index.cshtml
$.ajax({
type: "GET",
url: "/Home/Review",
success: function (data) {
$("#container").html(data);
//alert("yay");
}
...
<div id="container"></div>
Controller
public ActionResult Review()
{
return PartialView();
}
If you want to redirect after ajax you can use something like following:
Index.cshtml
$.ajax({
type: "GET",
url: "/Home/Review",
success: function (data) {
window.location.href = data.url;
}
...
Controller
public ActionResult Review()
{
return Json(new { url = "some url" }, JsonRequestBehavior.AllowGet);
}

Passing list to javascript to pass back to controller

I'm using ASP.NET MVC and my model has a list as part of it. I want to pass that list to a javascript function and inside this function I turn around and want to pass it back to a controller.
Currently I have:
#Html.ActionLink("Edit", "Edit", "Data", new { onclick = string.Format("EditRecord({0});", Model.Types) })
Model.Types is defined as List
My javascript EditRecord is defined as:
function EditRecord(types)
{
$.post("/Data/Edit/" { myTypes: types });
}
My controller is define as:
[HttpPost]
public ActionResult Edit(string[] myTypes)
{
return View();
}
When I run this I get page can't be found. If I switch this from the list to just a normal data type like an int or string then it all works, so something with the fact that it's an array is throwing this off. Any ideas?
Here goes my solution, Lets say you have a model holding List property in following way -
public class MyModel
{
public List<string> Types { get; set; }
}
This model will be constructed in the following controller action and will be returned to the View -
public ActionResult Index()
{
MyModel model = new MyModel();
model.Types = new List<string>();
model.Types.Add("Admin");
model.Types.Add("User");
model.Types.Add("SuperAdmin");
return View(model);
}
And the View has following Html -
#model Rami.Vemula.Dev.Mvc.Controllers.MyModel
#{
ViewBag.Title = "Home Page";
}
<div class="row">
Click me
</div>
Now the JQuery part which will hold the logic to send the List to the controller action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.Types = #Html.Raw(Json.Encode(Model.Types));
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) {
alert(data);
},
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
Then on clicking the button, it will hit the following controller -
public JsonResult GetJson(List<string> Types)
{
return Json(Types, JsonRequestBehavior.AllowGet);
}
When you click the button, and put a breakpoint to check the values -
By this your controller is returning blank view. Make sure that your view is created (right click-go to view). And if you want to return it it should be something like this:
rerurn View(myTypes);
But make sure that myTypes view is set up to accept string[].
if you want to pass your list to client consider ajax call that will send json object array and adjust your backend to accept it.

Why does my action not return a view?

I have this page, where I select an item from a dropdown list, and an ajax call passes along the selected parameter to a new action in my controller, like this:
function select(e) {
var unit = $("#unitList").data("kendoDropDownList").value();
var url = '#Url.Content("~/Reports/UnitRunReport/")';
$.ajax({
url: url,
data: { selectedUnit: unit },
type: 'GET',
dataType: 'json',
success: function (data) {
//
},
error: function () {
//
}
});
}
Here's my controller:
public class ReportsController : BaseController
{
public ReportsViewModel Model { get; set; }
//
// GET: /Reports/
public ActionResult Index()
{
Model = new ReportsViewModel
{
Units = UnitClient.GetListOfUnits(true, "")
};
return View(Model);
}
[HttpGet]
public ActionResult UnitRunReport(string selectedUnit)
{
var unit = Convert.ToInt32(selectedUnit);
Model = new ReportsViewModel
{
UnitRuns = RunClient.GetRunListForUnit(unit)
};
return View(Model);
}
}
I have to separate views for the two actions (Index and UnitRunReport). When debugging, it passes along the correct parameter to the UnitRunReport action, and moves through the return View(Model) statement. Could someone please explain why I'm not redirected to the new UnitRunReport View from the Index page?
You are in an ajax call. The ajax call will not redirect the page.
Redirect to the get method instead:
window.location = "#Url.Content("~/Reports/UnitRunReport")?selectedunit=" + $("#unitList").data("kendoDropDownList").value();
You are not redirected because you are making the call using ajax. This by definition means that the page will not change. The result of the ajax call (in this case the ActionResult returned by the UnitRunReport method) will be returned into the data parameter of the success delegate you are providing to jQuery.
You could fix this by passing in a success delegate to swap the html on the page (or in an element on the page with the result of the call) e.g. If you had an element with the id dataElement then use this in you success callback
success: function (data) {
$("#dataElement").html(data);
}
Note you are returning html back from your controller method. You may want to return a json model and bind that to your page using a library like knockout.
If you want to actually redirect to the page rather than making an ajax call like you are currently doing then you need to set the window.location property when the user changes the selection in the dropdown. This will cause the whole page to reload and render the view that UnitRunReport returns into a new page.
First of all you are making a ajax request which will not redirect the page but just read the data from the action.
Secondly, you are requesting for the json result which will give you the json data.
It looks like you're trying to get JSON data back rather than a view, which is typically HTML. So your controller should look like the following.
public class HomeController : Controller
{
public ReportsViewModel Model { get; set; }
//
// GET: /Reports/
public ActionResult Index()
{
Model = new ReportsViewModel
{
Units = UnitClient.GetListOfUnits(true, "")
};
return View(Model);
}
[HttpGet]
public ActionResult UnitRunReport(string selectedUnit)
{
var unit = Convert.ToInt32(selectedUnit);
Model = new ReportsViewModel
{
UnitRuns = RunClient.GetRunListForUnit(unit)
};
return this.Json(Model, JsonRequestBehavior.AllowGet);
}
}
You can test the data coming back in your javascript by doing a console.log. Also instead of doing Url.Content try Url.Action because your routes may not be setup correctly and url.action will make sure that the correct route will get generated.
function select(e) {
var unit = $("#unitList").data("kendoDropDownList").value();
var url = '#Url.Action("UnitRunReport", new { controller = "Home" })';
$.ajax({
url: url,
data: { selectedUnit: unit },
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
// do something with the data coming back
},
error: function () {
// show some sort of message
}
});
}
To view the console just hit F12 to get your tools to pop up in your favorite browser (I'm still a firebug fan). Just be careful about deploying anything with console.log into production, these days it doesn't usually matter because people have newer browsers but you may still get those one or two that will slip by and have issues. If you want to keep the code in there and put it into production you can launch a script with your pages into production to override console.log
<script type="text/javascript">
console = {
log: function (s) {
// empty method to override console
}
};
</script>
Put that in your site.master and remove it during development, you can keep all your console.logs and when going to production they'll stop showing up.
Because you're doing an Ajax call to the action method, so the view will be returned in the data parameter here: function (data)
It will not redirect the browser.

Action is unreachable after submitting a form

I have the following problem (I spend many hours looking for a solution).
The ‘Create’ button has a click event which calls the ‘Test’ action on the ‘Home’ controller.
All works fine.
When I hit the ‘Save’ button, to submit the form, that works fine to.
But after I have submitted the form, my ‘Create’ button stops working. The ‘Create’ button does have the click event, but the ‘Test’ action is unreachable?
index.cshtml
<script type="text/javascript">
$(document).ready(function () {
$("#create").click(function () {
$.ajax({
type: "POST",
traditional: true,
url: 'Home/Test',
dataType: "html",
success: function (data) {
alert('Succes!')
},
error: function () {
alert('A problem ocurred!!');
}
});
});
});
</script>
<input id="create" type="button" value="Create" />
#using (Html.BeginForm("SaveForm", "Home"))
{
<input type="submit" value="Save" />
}
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult Test()
{
return Content("Test result");
}
public ActionResult SaveForm()
{
return View("Index");
}
public ActionResult About()
{
return View();
}
}
All of your actions are GET only. Either add [HttpPost] (POST only) or [AcceptVerbs(HttpVerbs.Post, HttpVerbs.Get)] (GET or POST) attributes to your POST actions.
[HttpPost]
public ActionResult Test()
{
return Content("Test result");
}
[HttpPost]
public ActionResult SaveForm()
{
return View("Index");
}
Theres 2 problems:
1) you dont have [HttpPost] above your methods
2) You are not sending any data to your controller
add an id to your form by using an anonymous class:
#using (Html.BeginForm("SaveForm", "Home", new {id = "testform"}))
then rewrite the ajax request:
<script type="text/javascript">
$(document).ready(function () {
$("#create").click(function () {
$.ajax({
type: "POST",
data: $("#testform").serialize();
url: 'Home/Test',
dataType: "html",
success: function (data) {
alert('Succes!')
},
error: function () {
alert('A problem ocurred!!');
}
});
});
});
</script>
Let me know if it works :)
To create an entity, you have to submit your data to server, either by post back or ajax as in your case. Now there are some contradictions in your code :)
1. Why are you calling one action as form action and another through
ajax? Because since your button will post back, your ajax call won't
fire the success and error handlers. To solve this either use <button> or
$("#create").click(function (e) { e.preventDefault();//Some code});
2. If you want to use ajax, write it like this. Also write [HttpPost] on
your action. This indicates that this action can be called by post requests.
This is a required step, whether or not you are using ajax.
I hope this solved your problem.
Eventually I used Ajax.BeginForm instead of Html.BeginForm, added the [HttpPost] attributes to my actions and I used the RedirectToAction("Index") instead of PartialView. That solved my problem. Thanks again for your tips!

Categories