JQuery AJAX HandleErrorAtribute PartialView - asp.net-mvc

I have a function that submits a form to a MVC controller as follows -
function submitForm() {
$.ajax
({
type: 'POST',
url: '/Users/Index',
data: $('#searchForm').serialize(),
beforeSend: function() {
$('.usersearchresult').fadeOut('fast', function () { $('.loadinggif').show(); });
},
success: function (response) {
$('.loadinggif').hide();
$('.usersearchresult').hide().html(response).fadeIn('normal');
},
error: function (response) {
alert(response);
$('.loadinggif').hide();
$('.usersearchresult').hide().html(response).fadeIn('normal');
}
});
return false;
}
I wanted a central location to catch errors so I have extended HandleErrorAttribute -
public class ClientExceptionAttribute : HandleErrorAttribute
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public override void OnException(ExceptionContext context)
{
Log.Error(context.Exception);
context.ExceptionHandled = true;
// Verify if AJAX request
if (context.HttpContext.Request.IsAjaxRequest())
{
// Use partial view in case of AJAX request
var result = new PartialViewResult();
result.ViewName = "~/views/shared/error.ascx";
context.Result = result;
}
}
}
The error view is very simple -
#model String
#{
Layout = null;
}
<div class="exception">
<img src="../Content/Graphics/warning.png" />
<br />
<div class="message">#(String.IsNullOrEmpty(Model) ? "User Entry Api is currently unavailable" : Model) </div>
</div>
The problem is that AJAX on error never renders the partial view (error.cshtml) - it just gives me a blank screen.
So I have two questions -
How do I make AJAX render the partial error view
How can I pass a model to a partial view in the ClientExceptionAttribute
Thank you!

result.ViewName = "~/views/shared/error.ascx"; should be result.ViewName = "Error";
If anyone knows the answer to question number two I'd appreciate it.

Related

CORS error on trying to call controller action method with return type view from another application

Am trying to trigger the Post method of application-1 and open in new window or tab.
Application-1
public class TestController : Controller
{
[HttpPost]
public ActionResult PostSearch(object searchInput)
{
return RedirectToAction("Index", "Studnet")
}
}
want to trigger this post method from application-2.
<input type="button" id="search"
value="Trigger Post" onclick="TriggerPostSearch('1234')"/>
function TriggerPostSearch(searchObject) {
var url = "http://www.localhost:99/test/PostSearch";
OpenWindowWithPost(url, searchObject);
};
function OpenWindowWithPost(url, model) {
var param = { "searchInput": model };
$.ajax({
url: url,
type: "POST",
contentType: "application/json",
data:param
}).done(function(result){
window.open(url, '_blank');
});
}
Enabled CORS in app-1 to accept request from app-2. Is there any otherway of doing this?

MVC: Result from JSON Automatically fill View

I am stuck in publishing the result from JSON so left the success portion blank.
View
#model MvcApplication2.Models.About
#{
ViewBag.Title = "About";
}
<p> #Html.DisplayFor(m=>m.test) </p>
<p> #Html.DisplayFor(m=>m.test1) </p>
Model
public class About
{
public string test { get; set; }
public string test1 { get; set; }
}
Controller
public class HomeController : Controller
{
public JsonResult About()
{
ViewBag.Message = "Your app description page.";
About ab = new About()
{
test = "a",
test1 = "b"
};
return Json(ab, JsonRequestBehavior.AllowGet);
}
}
JQuery in external file
$(document).ready(function () {
var itemName = "#btn-about";
$(itemName).click(function () {
$.ajax({
type: 'GET',
dataType: 'Json',
url: '/Home/About',
success: function (data) {
var option = '';
},
error: function (xhr, ajaxOption, thorwnError) {
console.log("Error")
},
processData: false,
async: true
});
});
});
=> I am a bit confused now. Altough I get a result in JSON format using AJAX, I want to publish it in this View 'About'. The View already have #model defined, so as soon as I get the result, I want the view to load it automatically as I don't think its a good option to create html controls in Javascript.
=> Is it possible or do I have to fill control one by one.
=> I am new in to MVC, so could you let me know any good suggestion.
Controller:
public ActionResult About()
{
var model = repo.GetModel();
return PartialViewResult("about", model);
}
jQuery:
$.ajax("/Controller/About/", {
type: "GET",
success: function (view) {
$("#aboutDiv").html(view);
}
});
In Main View:
<div id="aboutDiv"><div>
You need to give your elements some id or class that will allow you to interact with them easily on the client. Then, when you get your response, take the values from the JSON data and update the elements (using the id/class to find it) with the new value. I'm assuming you don't have any special template defined for your strings, adjust the selectors in the code as necessary to account for it if you do.
View
<p class="testDisplay"> #Html.DisplayFor(m=>m.test) </p>
<p class="test1Display"> #Html.DisplayFor(m=>m.test1) </p>
Client code
$(document).ready(function () {
var itemName = "#btn-about";
$(itemName).click(function () {
$.ajax({
type: 'GET',
dataType: 'Json',
url: '/Home/About',
success: function (data) {
$('.testDisplay').html(data.test);
$('.test1Display').html(data.test1);
},
error: function (xhr, ajaxOption, thorwnError) {
console.log("Error")
},
processData: false,
async: true
});
});
});
Instead of returning the data you will have to return the view as string and the use jquery to replace the result.
Controller:
public JsonResult About()
{
var model = // Your Model
return Json((RenderRazorViewToString("ViewNameYouWantToReturn", model)), JsonRequestBehavior.AllowGet);
}
[NonAction]
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();
}
}
Then using jquery you can replace the result in container for eg: div as follows:
$.ajax({
type: 'GET',
dataType: 'Json',
url: '/Home/About',
success: function (result) {
$("#divId").replaceWith(result);
},

Print out to a div in the view from the controller

I have a div block in my view like this:
<div id="divStatus" style="margin-top:10px;width: 200px; height: 100px; overflow-y: scroll;">
</div>
then from the view, user clicks on a button that calls the controller. In the controller some tasks are executed so from the controller I want to update a div block within the view. In this div I print out phrasses.
How to do this?
example:
public ActionResult()
{
// Do something
Update_DIV_in_View("some thing has been done"); <--- DIV in the view must be updated by appending this message
// Do another thing
Update_DIV_in_VIEW("another thing has been done");<--- DIV in the view must be updated by appending this message
.... and so on
// All things done
Update_DIV_in_VIEW("All things have been done");<--- DIV in the view must be updated by appending this message
return View();
}
Create a second action in your controller which only shows the updated content of the div and on your normal page when you press the button load the status with an AJAX call (for example the jQuery.load() method).
You can do it as follows:
In your view use Ajax Form as follows:
#using (Ajax.BeginForm("ActionName", "ControllerName", new AjaxOptions { OnBegin = "beforeSubmitFunction()", HttpMethod = "POST",UpdateTargetId = "divStatus", OnComplete = "InsertRow()" }))
{
.. //your Html form Controls
}
function beforeSubmitFunction()
{
//Your code for before submitting...
}
Then in your controller return your partial view as result which will get updated in your div with id divStatus
[HttpPost]
public ActionResult Index(TypeName model)
{
return PartialView("PartialViewName", model);
}
Here are 3 examples what I am using:
example 1:
button (here with telerik css styling):
<a class="t-button t-button-icontext" onclick="ajaxCreateEquipment()"><span
class="t-icon t-add"></span>Create</a>
javascript: #equipment-table-container is the id of the target div:
<script type="text/javascript">
function ajaxCreateEquipment() {
$.ajax({
type: 'GET',
url: '#Url.Action("ShowCreate", "Equipment")',
dataType: 'html',
success: function (data) {
$('#equipment-table-container').html(data);
}
});
}
</script>
EquipmentController.cs:
[HttpGet]
public ActionResult ShowCreate()
{
// some calculation code, fetch model from DB something else
ViewData.Add("FormAction", "Create"); // some ViewData
return PartialView("Create", model); // returns the View html file
}
example 2:
function call here with id argument and Json return:
#{
var supplierQuoteId = Model.ID.ToString();
<a id="#supplierQuoteId" onclick="updateDiv(this.id)"></a>
}
javascript:
function updateDiv(id) {
var strUrl = "/LicenseTerm/UpdateUsedQuantity/" + id;
$.ajax({
type: "GET",
url: strUrl,
cache: false,
dataType: "json",
success: function (data) {
$('#licenseterm-usedquantity').html(data.sum);
}
});
}
LicenseTermController.cs
[HttpGet]
public JsonResult UpdateUsedQuantity(Guid id)
{
var licenseTerm = _repository.GetAll<LicenseTerm>().Where(l => l.ID == id).First();
int sum = 0;
foreach (LicenseAllocation l in licenseTerm.LicenseAllocations.Where(o => o.Deleted == false))
sum = sum + l.LicenseQuantity;
return Json(new { sum = sum }, JsonRequestBehavior.AllowGet);
}
example 3: simple get
function ajaxFieldDefinitionCreate(id) {
var strUrl = '/FieldDefinition/Create' + '/' + id.toString() + '?isRefreshAction=true';
$.get(strUrl, function (data) {
$('#equipmenttype-fielddefinition-createeditarea').html(data);
});
}
[HttpGet]
public ActionResult Create(Guid id, [Optional, DefaultParameterValue(false)] bool isRefreshAction)
{
var equipmentType = _equipmentTypeRepository.GetById(id);
var fieldDefinitionDto = new FieldDefinitionDto
{
ID = Guid.NewGuid(),
ParentName = equipmentType.Name,
};
return PartialView("Create", fieldDefinitionDto);
}
In response to the changes of the question, especially that the questioner would like to have more returns in the same Action:
the concept of HTTP request is to transmit relatively small pieces of data from the server to the client, which invoked the e.g. HTTP GET request.
You can not keep open the HTTP GET request for more transmissions.
I searched the web and extracted that especially HTML5 will address this requirement with the HTTP stream, but this is another topic. e.g.: I got this url: http://socket.io/ .
Bypass:
But as an idea of mine,
I would make a first ajax call to determine the count of the next requests, addressed in the controller Action1.
And then invoke several new requests in the success part of the first ajax request, with the url of the Action2, e.g. Calculate etc., which appends then the several pieces of data to the div content.
here some quickly invented javascript code:
function updateDiv() {
var strUrl = "/Home/RequestCount/";
$.ajax({
type: "GET",
url: strUrl,
cache: false,
dataType: "json",
success: function (count) {
var strUrlCalc = "/Home/Calc/";
for (var i = 0; i < count; i++) {
$.ajax({
type: "GET",
url: strUrlCalc,
cache: false,
dataType: "json",
success: function (data) {
$('#test').append(data);
}
});
}
}
});
}

Post from partial View change the URL

I have a partial view with a contact form.
My problem is that after the form is posted, the controller is redirecting to the actual URL of the partial view: ("LocalHost:/Views/ContactUs/MoreInformationRequest.cshtml")
I want to keep the same URL and to show only the ViewData["MsgSent"] message.
This is the call to the partial view:
#Html.Partial("~/Views/ContactUs/MoreInformationRequest.cshtml")
The View:
#using (Html.BeginForm( "MoreInformationRequest","ContactUs"))
{
.....
<input type="submit" value="send" /><br />
#ViewData["MsgSent"]
}
The Controller:
[HttpPost]
public ActionResult MoreInformationRequest(ContactUs contacts)
{
.....
ViewData["MsgSent"] = "Message sent!"
return View();
}
You could use a redirect to redisplay the page that loads the partial view:
return RedirectToAction("OriginalAction");
You could also return a specific view, particularly the view from the original action:
return View("OriginalView");
post to the server using jQuery and return false from the javascript function to stop the default processing (i.e. sending to the new url from the controller.
At the beginning I came out with this solution - to redirect to the same page using:
Request.Redirect("~/");
But I did not like this solution so I solved this by using client side code to send the data to the controller:
<script>
var request;
$('#formMoreInformationRequest').submit(function () {
var Name = document.getElementById('Name');
var Phone = document.getElementById('Phone');
// without this the validations in the page are not working.
if (Name.value == "") {
return false;}
else if (Phone.value == "") {
return false; }
else {
$('#overlay').show()
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/ContactUs/MoreInformationRequest",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
$('#overlay').hide()
$("#moreInfoMsg").html("Message Sent!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown) {
$('#overlay').hide()
// log the error to the console
alert(
"The following error occured: " +
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
}
</script>

View not refreshing after AJAX post

I have a view (Index.cshtml) with a grid (Infragistics JQuery grid) with an imagelink. If a user clicks on this link the following jquery function will be called:
function ConfirmSettingEnddateRemarkToYesterday(remarkID) {
//Some code...
//Call to action.
$.post("Home/SetEnddateRemarkToYesterday", { remarkID: remarkID }, function (result) {
//alert('Succes: ' + remarkID);
//window.location.reload();
//$('#remarksgrid').html(result);
});
}
Commented out you can see an alert for myself and 2 attempts to refresh the view. The location.reload() works, but is basically too much work for the browser. The .html(result) posts the entire index.cshtml + Layout.cshtml double in the remarksgrid div. So that is not correct.
This is the action it calls (SetEnddateRemarkToYesterday):
public ActionResult SetEnddateRemarkToYesterday(int remarkID) {
//Some logic to persist the change to DB.
return RedirectToAction("Index");
}
This is the action it redirects to:
[HttpGet]
public ActionResult Index() {
//Some code to retrieve updated remarks.
//Remarks is pseudo for List<Of Remark>
return View(Remarks);
}
If I don't do window.location.reload after the succesfull AJAX post the view will never reload. I'm new to MVC, but i'm sure there's a better way to do this. I'm not understanding something fundamental here. Perhaps a nudge in the right direction? Thank you in advance.
As you requesting AJAX call, you should redirect using its response
Modify your controller to return JSONResult with landing url:
public ActionResult SetEnddateRemarkToYesterday(int remarkID) {
//Some logic to persist the change to DB.
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Controller");
return Json(new { Url = redirectUrl });
}
JS Call:
$.post("Home/SetEnddateRemarkToYesterday", { remarkID: remarkID }, function (result) {
window.location.href = result.Url
});
After Ajax post you need to call to specific Url..
like this..
window.location.href = Url
When using jQuery.post the new page is returned via the .done method
jQuery
jQuery.post("Controller/Action", { d1: "test", d2: "test" })
.done(function (data) {
jQuery('#reload').html(data);
});
HTML
<body id="reload">
For me this works. First, I created id="reload" in my form and then using the solution provided by Colin and using Ajax sent data to controller and refreshed my form.
That looks my controller:
[Authorize(Roles = "User")]
[HttpGet]
public IActionResult Action()
{
var model = _service.Get()...;
return View(model);
}
[Authorize(Roles = "User")]
[HttpPost]
public IActionResult Action(object someData)
{
var model = _service.Get()...;
return View(model);
}
View:
<form id="reload" asp-action="Action" asp-controller="Controller" method="post">
.
.
.
</form>
Javascript function and inside this function I added this block:
$.ajax({
url: "/Controller/Action",
type: 'POST',
data: {
__RequestVerificationToken: token, // if you are using identity User
someData: someData
},
success: function (data) {
console.log("Success")
console.log(data);
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(data, 'text/html'); // parse result (type string format HTML)
console.log(htmlDoc);
var form = htmlDoc.getElementById('reload'); // get my form to refresh
console.log(form);
jQuery('#reload').html(form); // refresh form
},
error: function (error) {
console.log("error is " + error);
}
});

Resources