Reputation: 3629
I would like to return error html text with "IsError" flag.
How could I implement it?
Here is my trial.
Assuming that I submitted the Ajax.BeginForm and error occured on server side.
Global.asax
void Application_Error(Object sender, EventArgs e)
{
var exception = Server.GetLastError();
var number = GetErrorNumber();
Server.ClearError();
Response.Redirect("/Error?number=" + number, false);
}
View Error/index
<div>
An error occurred<br>
Error number : @ViewBag.ErrorNumber
</div>
ErrorController I want to return JSON including view html and "IsError = true"!!
ViewBag.ErrorNumber = number;
return View();
Client side JavaScript catches the returned value.
And the returned html text would renders if "IsError" was true.(I wish)
Upvotes: 0
Views: 989
Reputation: 15276
Your need seems unusal wich is often an indication of a problem elsewhere.
I would suggest the following approach:
Here's an example on your action:
public ActionResult FormPostHandler()
{
try
{
// Process request
}
catch (Exception ex)
{
if (Request.IsAjaxRequest())
{
return Json(new
{
Success = false,
ErrorNo = 1
});
}
else
{
return View("ErrorView"); // add model for error
}
}
}
UPDATE:
After reading your question again I might have figured out what you're trying to achieve.
Success
is false and add it to your HTML DOM.I would say it's bad practice to return html with JSON, it's better to let JSON just carry information and let your presentation layer (html & javascript) handle the appearance.
If you're using jQuery, prototype etc this should be quite straightforward.
Upvotes: 0
Reputation: 13150
I think you should return json and create the HTML DIV on client side using javascript. I think you can not return HTML in json.
Upvotes: 1