简体   繁体   中英

JQuery and Razor Controller View ActionResult

I have a controller who can return a Success or Error page like this:

[HttpPost]
public ActionResult File_post(HttpPostedFileBase file)
{
   if (...)
      return View("Success");
   else
      return View("Error");
}

Those Success and Error pages contains only basic text and are displayed in the Shared/_Layout.cshtml.

In my js I want to call those pages defined by the return View, but how can I do that ?

I tested : window.location.reload();
Which works but it only reloads the actual Index page.
If I try : window.location.href = data.url;
It fails because the page http://xxx/xxx/File_post doesn't exists.
And if I do : $('#main').html(data);
The page have the good looking but the content is empty.

Edit: I am using jquery.fileupload so I have :

 <input id="fileupload" type="file" name="file" />

and

$('#fileupload').fileupload(
{
  done: function (e, data) {
    // Use the return View("Success")
  },
  fail: function (e, data) {
    // Use the return View("Error")
  }
});

In my jqXHR.reponseText and data.result there is the good "Success" or "Error" html so I think I need to fill the page with this but how ?

Any ideas ? thanks a lot !

I found how to do it. As I have in my Layout a <div id="main"> I can use my data.result to fill the page with my "Success" or "Error" message. So I have :

done: function (e, data) {
  $('#main').html(data.result);
}

And

return PartialView("Success");

Now the page is correctly displayed.

You can try with this code

$.ajax({
 type: "POST",
 url: Settings.YourUrl,
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
 alert("here" + data.d.toString());
});

And in your View you can add this code

var Settings= {
    YourUrl: '@Url.Action("Action","Controller")'
}

The current action can handle only POST requests. So you can create another action to return the view for GET request.

Ex.

public ViewResult Success()
{
   return View();
}

you can changed the statusCode to 500 or error code you need;

C#

[HttpPost]
public ActionResult File_post(HttpPostedFileBase file)
{
   if (...) 
   {
      return View("Success");
   }
   else
   {
      Response.StatusCode = 500;
      Response.TrySkipIisCustomErrors = true; 
      return View("Error");
   }
}

JS:

$('#fileupload').fileupload(
{
  done: function (e, data) {
    // Use the return View("Success")
  },
  fail: function (e, data) { // http status response != 200
    // Use the return View("Error")
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM