Nigiri
Nigiri

Reputation: 3629

How to return JSON including the html text of the view

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

Answers (2)

Jonas Stensved
Jonas Stensved

Reputation: 15276

Your need seems unusal wich is often an indication of a problem elsewhere.

I would suggest the following approach:

  1. Catch the error in the action with a standard try-catch.
  2. Check if it is an ajax request with IsAjaxRequest and return json if true, otherwise return a standard html view

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.

  1. Use the above code to output a json result.
  2. On the client-side, create the html needed to show your error if 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

Asif Mushtaq
Asif Mushtaq

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

Related Questions