07_05_GuyT
07_05_GuyT

Reputation: 2887

Not able to call to view from action

Im having a view which I use in multiple actions to send error to user ,this view are working fine with when I return it to ActionResult but not for JsonReslut ,there is a way somehow to call to this view when I return JsonReslut ?some workaround?

For example this is working

public ActionResult Index()
{
...

return View("Err");
}

This is not working

public JsonResult Create ()
{
...

return View("Err");
}

This is only view page without any controller or model ...

Upvotes: 0

Views: 158

Answers (4)

user3762266
user3762266

Reputation:

public JsonResult Create ()
{
 ...
 return RenderRazorViewToString(viewname,model);
}


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();
}

Upvotes: 1

James S
James S

Reputation: 3588

You don't return a view for JsonResult.

try something like:

[HttpPost]
public ActionResult Create (ModelClass newItem)
{
  int newItemId = -1;
  string message = "";
  bool createdOk = false;
  try{
     newItemId = CreateNewItemInDatabase(newItem); //example - you'd need a proper implementation!
  }
  catch (Exception ex)
  {
     message = "Error: " + ex.Message;
  }
  return Json(new {ErrMessage = message, Ok = createdOk, newItemId = newItemId}) //example. Any object would do.
}

ViewResult and JsonResult both inherit from ActionResult.

JsonResult does not inherit from ViewResult!

The View that interacts with this might look like:

@model ModelClass
<form id="MyNewForm">
  @Html.TextBoxFor(m => m.Name)
  @Html.TextBoxFor(m => m.EmailAddress) //etc
  <input type ="button" value="Create" onClick="create();" />
</form>

<script>
  // javascript function that calls the Create Action Method via ajax
  function create(){
    $.post({
      url : 'Create',
      data: $('#MyNewForm').serialize(),
      success: function (result){ // this is a callback function that gets executed
                                  // after getting the results of the ajax post
        if (result.Ok)
        {
          alert('New item with id:' + result.NewItemId + ' created successfully!');
        } else
        {
          alert('Failed to create item: ' + result.ErrMessage); 
        }
      }
    });
  }
</script>

NB this is an example only, and might have errors. I've used jQuery in this example, but you could do pure javascript if you prefer

Upvotes: 1

Artur Kedzior
Artur Kedzior

Reputation: 4263

I assume that you call this action with javascript. If so, you should return return something like this:

public JsonResult Create ()
{
...
return Json(new { status = "error", redirect = "error_page_url" }, JsonRequestBehavior.AllowGet); 
}

Then handle the error in javascript (do the redirect to error page)

Here is an example using jQuery:

$.ajax({
    type: "get", url: "/controller/Create", dataType : "json",
    success: function (response) {
        if (response.status == "error") {
            window.location.href = response.redirect;
        }
        else {
            // process results...
        }
    },
    error: function (request, status, error) {
        alert(request.responseText);
    }
});

Upvotes: 1

malkam
malkam

Reputation: 2355

You can have one common action for Errors and redirect to this action on error

public ActionResult Error()
{
 return View("Err");
}
public ActionResult Index()
{
...

return RedirectToAction("Error");
}

public ActionResult Create ()
{
...

return RedirectToAction("Error");
}

Upvotes: 1

Related Questions