Redirecting to error page if a partial view encounters an error [duplicate] - asp.net-mvc-3

This question already has answers here:
ASP.NET MVC Custom Error Handling Application_Error Global.asax?
(10 answers)
Closed 2 years ago.
I'm rendering a partial view inside of a view:
#{
Html.RenderAction("PartialViewAction", "SomeController");
}
Is there a way to redirect the user to an error page if the partial view action encounters an error?
EDIT: I'm looking for a server side kind of redirection. This partial view is not loaded with AJAX. It is rendered server side into a "big" view. The "big" view has no idea that the partial view errored out.

Depending on your logic, you might be able to control your application flow by using jQuery.ajax() to handle errors.
// this will render the GET request on page load
$(function() {
$.ajax({
url: '/Some/PartialViewAction',
type: 'GET',
dataType: 'json', /*edit*/
success: function(xhr_data) { /*edit*/
// the following assumes you wrap
// your partial view in div id="myDiv"
$('#myDiv').html(xhr_data.html); /*edit*/
$('#myErrorDiv').html(xhr_data.error); /*edit*/
},
error: function() {
window.location.href='/Some/Error';
// or similar page redirecting technique
}
});
});
This will handle an error in the GET, but of course if you were to return some JSON or some other indicator in your action method, you could use the same window.location.href... in the success callback function.
Edit
Also see above edits to $.ajax
Your controller could do something like this:
public ActionResult PartialViewAction() {
// handle error
string message = "Evacuate, Immediately!";
// not certain the html will render correctly,
// but you could encode/parse/whatever easily enough
return Json(new { html = "<div>some html</div>", error = message },
JsonRequestBehavior.AllowGet);
}

Related

Using Razor Pages coredotnet how can I load a partial view via ajax

In using Razor pages, it is simple to use partial using #Html.Partial(..).
However, when a drop down changes, I want to refresh part of the view - the part rendered by the partial view.
I have searched lots, and found answers such as: https://github.com/aspnet/Razor/issues/2073 where they say partials are meant for code behind.
Is there a reasonable workaround such that I can re-render a subset of the view which is defined in a partial view? What is the best practice way of achieving this?
Yes,
Have an action method that can be called to reload just the partial view:
public ActionResult Reload()
{
return PartialView("NameOfPartialView");
}
Get it from the client (I'll use jQuery):
$.ajax({
type: "post",
url: "Reload",
data: {},
success: function(d) {
//d is the HTML content returned from the Action Method
$("#parentelementaroundinnerdata").html(d);
}
});
Returning the partial view from the action method returns an HTML string, and that can be injected into the page using a parent element to replace its contents with the update. That means when rendering the original, have the setup as the following:
<div id="parentelementaroundinnerdata">
#Html.Partial("NameOfPartialView")
</div>
You can use the same partial from an AJAX request and for loading an initial result - sometimes you have to be careful within the partial on what is going on because of that though...

CakePHP 3 and partial View update via Ajax - How it should be implemented?

I want to render a cakephp3 template by ajax and inject the html into a loaded page (without reloading the page).
According to
CakePHP 3 and partial View update via Ajax - How it should be done?,
the idea can be
Create dedicated template (*.ctp) file for every ajax action, render
it like any other action but without the main layout and inject the
HTML (kind of variant 1 but with separated VC logic).
It also provides a partial example code:
public function ajaxRenderAuditDetails($id = null)
{
if ($id == null) {
return null;
}
if ($this->request->is("ajax")) {
$this->set("result", $this->viewBuilder()->build()->cell("audits", [$id]));
}
}
May anyone suggest a full example?
For this you have to use a Ajax call for get data from server. In term of CakePhp you will call a controller function using Ajax. This function call a ctp file which render your partial view. Success function of Ajax should updated or append the partial view. A complete example code for this process is here -
Ajax code for call controller function -
$.ajax({
dataType: 'json',
url: basepath/controllername/controllerfunction,
type: "POST",
dataType : 'html',
success: function (data) {
$(selector).html(data);
}
});
public function ajaxRenderAuditDetails($id = null){
$this->viewBuilder()->layout(false);
if ($id == null) {
return null;
}
if ($this->request->is("ajax")) {
$this->set("result", $this->viewBuilder()->build()->cell("audits", [$id]));
}
}
Put your required html or logics in ctp file.
This is not a running code. It is sample example for updating partial view in CakePhp.

success function equivalent for httppost in mvc

What is the equivalent for success function when I am using [HttpPost] in MVC instead of ajax calls
in ajax, for calling controller in MVC I use something like
$.ajax({
url: '#Url.Action("SomeConroller", "ActionName")',
dataType: 'html', //be sure to use html dataType
contentType: 'application/json; charset=utf-8',
success:someFunctionName
});
I stopped using ajax calls and started using ajax and started using [HttpPost] so that all input type="submit" will come to that and i will handle the events to be done.
Now there is a scenario where I am selecting and moving an item to a different list, and after its done i am doing a this.RedirectToAction("ActionName", "ControllerName");
The problem is, once it is done how can i alert that it is moved? if it is ajax i will handle it in success function. Where can i handle that here?
Since you are redirecting to another action, the page will refresh. If you want to display an alert on new page, the action view can display it with the data you pass to the view.
So something like this should give action data that it pass to the view:
return RedirectToAction("TargetAction", "Controller", new {id = userId});
The "TargetAction" will prepare a view model object and return a view with the view model:
return View(viewModel);
View will have logic to display a alert with custom text. E.g. if you want to display javascript alert on load, just define
$(document).ready(function () {
alert("Item moved: " + '#Model.Id');
});

angularjs changes in data not affected in views ajax

I am developing an application with angular js
Question: When I have an ajax call to server and I need to change the views based on the result of ajax call, the views don't get affected by this call, I think it the page renders before ajax call is finished but I don't know how to resolve it
For example the following piece of code
$scope.addItem = function() {
$http({
method :'GET',
url : 'addItem',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success( function(data) {
$scope.allItems = data;
});
}
the allItems changed after the ajax call but the view is not changed
how should I solve this?

How to avoid redirect after form submission if you have a URL in your form's action?

I have a form that looks like this:
<form name="formi" method="post" action="http://domain.name/folder/UserSignUp?f=111222&postMethod=HTML&m=0&j=MAS2" style="display:none">
...
<button type="submit" class="moreinfo-send moreinfo-button" tabindex="1006">Subscribe</button>
In the script file I have this code segment where I submit the datas, while in a modal box I say thank you for the subscribers after they passed the validation.
function () {
$.ajax({
url: 'data/moreinfo.php',
data: $('#moreinfo-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#moreinfo-container .moreinfo-loading').fadeOut(200, function () {
$('form[name=formi]').submit();
$('#moreinfo-container .moreinfo-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
Unfortunately, after I submit the datas, I'm navigated to the domain given in the form's action. I tried to insert return false; in the code (first into the form tag, then into the js code) but then the datas were not inserted into the database. What do I need to do if I just want to post the data and stay on my site and give my own feedback.
I edited Eric Martin's SimpleModal Contact Form, so if more code would be necessary to solve my problem, you can check the original here: http://www.ericmmartin.com/projects/simplemodal-demos/ (Contact Form)
Usually returning false is enough to prevent form submission, so double check your code. It should be something like this
$('form[name="formi"]').submit(function() {
$.ajax(...); // do your ajax call here
return false; // this prevent form submission
});
Update
Here is the full answer to your comment
I tried this, but it didn't work. I need to submit the data in the succes part, no?
Maybe, it depends from your logic and your exact needs. Normally to do what you asking for I use the jQuery Form Plugin which handle this kind of behavior pretty well.
From your comment I see that you're not submitting the form itself with the $.ajax call, but you retrieve some kind of data from that call, isn't it? Then you have two choices here:
With plain jQuery (no form plugin)
$('form[name="formi"]').submit(function() {
$.ajax(...); // your existing ajax call
// this will post the form using ajax
$.post($(this).attr('action'), { /* pass here form data */ }, function(data) {
// here you have server response from form submission in data
})
// this prevent form submission
return false;
});
With form plugin it's the same, but you don't have to handle form data retrieval (the commented part above) and return false, because the plugin handle this for you. The code would be
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm(function() {
// this call back is executed when the form is submitted with success
$.ajax(...); // your existing ajax call
});
});
That's it. Keep in mind that with the above code your existing ajax call will be executed after the form submission. So if this is a problem for your needs, you should change the code above and use the alternative ajaxForm call which accepts an options object. So the above code could be rewritten as
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm({
beforeSubmit: function() { $.ajax(...); /* your existing ajax call */},
success: function(data) { /* handle form success here if you need that */ }
});
});

Resources