JQuery and Razor Controller View ActionResult - c#

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

Related

How to trigger controller and open new page (along with model) with ajax

I have a link. Its triggers my ajax. I want to open a new page after this triger.
But it's returning back to my ajax after the trigger. There is my code.
HTML
<a onclick="SiparisYazdir(#item.id)" >Print</a>
ajax
function SiparisYazdir(id)
{
$.ajax({
url: '/Order/Print',
type: 'GET',
data: { "value": value, 'id': id } // value is taking from another method.
});
}
controller
public IActionResult Print(int value, int id)
{
//taking model here
return View(model);
}
return View(model) will return the html content of your view
you cant put this html into your desired tag
function SiparisYazdir(id)
{
$.ajax({
url: '/Order/Print',
type: 'GET',
data: { "value": value, 'id': id } // value is taking from another method.,
success:(result)=>{
$('your_desire_elemnt').html(result)
}
});
}
If you want to redirect to another page, I think there is no need ajax here
function SiparisYazdir(id) {
window.location.href = "/Home/Privacy?value=" + value + "&id=" + id;
}

Posting AJAX string to MVC Controller

I am trying to post a string (the name of the href the user clicked on) using AJAX to my MVC controller (which it will then use to filter my table results according to the string).
Whilst I have managed to get it to post (at-least according to the alerts) on the AJAX side, it doesn't seem to arrive properly on the controller side and is seen as null in my quick error capture (the if statement).
Please excuse the useless naming conventions for the moment. I've been going through countless methods to try and fix this, so will name properly when I've got a proper solution :).
I've been at work for this for a long while now and can't seem to solve the conundrum so any help is appreciated please! I'm very new to AJAX and MVC in general so I'm hoping it's a minor mistake. :) (FYI I have tried both post and get and both seem to yield the same result?)
Controller:
[Authorize]
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
using (CBREntities2 dc = new CBREntities2())
{
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
var safeItem = dc.Items.Where(a => a.Safe_ID == yarp).Select(s => new {
Serial_Number = s.Serial_Number,
Safe_ID = s.Safe_ID,
Date_of_Entry = s.Date_of_Entry,
Title_subject = s.Title_subject,
Document_Type = s.Document_Type,
Sender_of_Originator = s.Sender_of_Originator,
Reference_Number = s.Reference_Number,
Protective_Marking = s.Protective_Marking,
Number_recieved_produced = s.Number_recieved_produced,
copy_number = s.copy_number,
Status = s.Status,
Same_day_Loan = s.Same_day_Loan
}).ToList();
// var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
}
}
AJAX function (on View page):
$('.tablecontainer').on('click', 'a.safeLink', function (e) {
e.preventDefault();
var yarp = $(this).attr('safesel');
var selectedSafeZZ = JSON.stringify("SEC-1000");
$.ajax({
url: '/Home/GetSafeItems',
data: { 'yarp': JSON.stringify(yarp) },
type: "GET",
success: function (data) {
alert(yarp);
console.log("We WIN " + data)
},
error: function (xhr) {
alert("Boohooo");
}
});
})
** The Alert reveals the correct type: "SEC-1000"
But the console Log shows: WE WIN [Object object]??
I have tried something basic in a new mvc dummy project :
View page basic textbox and a button :
<input type="text" id="txt_test" value="test"/>
<button type="button" class="btn" onclick="test()">Test</button>
<script type="text/javascript">
function test()
{
var text = $("#txt_test")[0].value;
$.ajax({
url: '#Url.RouteUrl(new{ action="GetSafeItems", controller="Home"})',
// edit
// data: {yarp: JSON.stringify(text)},
data: {yarp: text},
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
// edit
// alert(JSON.stringify(data));
alert(data.data);
}});
}
</script>
Controller :
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
return Json(new {data = string.Format("Back end return : {0}",yarp)}
, JsonRequestBehavior.AllowGet);
}
Alert result => {"data":"Back end return : \"test\""}
It's a simple ajax call to a web method. You don't return a view, so I don't understand the use of
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
Also I see an [Authorize] attribute, you perhaps use some authentication and I don't see any authentication header on your ajax call
Try this:
$.each(data, function (i) { console.log("We WIN " + data[i].Serial_Number )});

MVC action controller not rendering the page

after a compiling a form needed for register on the website( Registration.cshtml ), the form data are sent in a sqlite db ( successfully). Returning from that, i want to be sent to a Main.cshtml webpage. The problem is that the Action controller that is suposed to render the Main.cshtml view, isn't doing it.
I've tryed changing the Redirect/RedirectToAction and View methods many times, but it was a failure.
return View("Main");
return RedirectToAction("Main");
return JavaScript("window.location = window.location.origin + /Pages/Main");
PagesController.cs
[HttpPost]
public ActionResult Register {
if (insert data in db == true) {
return RedirectToAction("Main");
}
return View();
}
public ActionResult Main(){
return View();
}
Main.cshtml
#{
Layout = "~/Views/Layouts/LoggedMasterPage.cshtml";
ViewBag.Title = "Benvenuto in ETL365";
}
#section Head{
<link rel="stylesheet" href="~/Content/Main.css" />
<script type="text/javascript" src="~/Scripts/Main.js"></script>
}
Part of my Register.js
$("#register").dxButton({
text: "Registrati",
type: "normal",
hint: "Clicca per registrarti",
onClick: function () {
if($('#password').
dxValidator('instance').validate().isValid &&
$('#email').dxValidator('instance').validate().isValid) {
let email = $("#email").dxTextBox('instance').option('value');
let pass = $("#password").dxTextBox('instance').option('value');
$.ajax({
url: window.location.origin + '/Pages/Register',
type: "POST",
data: '{"email":"' + email + '","password":"' + pass + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
}
});
I've already used breakpoints on Main.cshtml, and it actually gets in there after the
return View();
done by the action Main().
What i expect is to be redirected to the mylocalhost:xxxx/Pages/Main
What i get is absolute nothing, I'm always in mylocalHost:xxxx/Pages/Register
You need to redirect to your main page after a successfull ajax call.
$.ajax({
...
success:
{
location.href = 'mylocalhost:xxxx/Pages/Main'
}
...
You cannot use RedirectToAction for AJAX call response because AJAX requests are intended to update the view without reloading whole page. You need to pass the URL as JSON response like this:
[HttpPost]
public ActionResult Register(string email, string password)
{
if (condition) // put your condition here
{
return Json(new {
status = "Success",
url = Url.Action("Main", "Pages")
});
}
// since this controller receives AJAX request, the partial view should be used instead
return PartialView("_Register");
}
Then in AJAX success condition you can check response status and redirect to target URL:
$.ajax({
url: '#Url.Action("Register", "Pages")',
type: "POST",
data: { email: email, password: pass },
success: function (result) {
if (typeof result.status !== undefined && result.status == "Success") {
location.href = result.url; // redirect to main page
}
else {
$('#register').html(result); // refresh partial view
}
}
});
Related issue:
return url.action as json object mvc

Sending Json with data with partial view

I have the following chtml code to an action in a controller. The data is being sent by ajax to the action.
The chtml part:
<li>
<button id="abandon-popup" onclick="Transfer(#Model.Id)">
Transfer <i class="icon-arrow-right"></i>
</button>
</li>
The function Transfer:
function Transfer(modelId) {
//alert(modelId);
$.ajax({
type: "GET",
url: "/Internet/Transfer",
data: "id=" + modelId,
success: function (responsedata) {
alert("ok");
window.location.href = responsedata.newUrl;
},
error: function (data) {
console.log("KO");
}
})
}
The action in the controller:
public ActionResult Transfer(long id)
{
*some actions*
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) });
}
However I am getting a 500 internal error on this:
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet
Any idea how to correct this?
Use this
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml",
commonModel
)}, JsonRequestBehavior.AllowGet);
By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking. You do not want to return sensitive information using JSON in a GET request.
Try this following:
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) });
into
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) }, JsonRequestBehavior.AllowGet);
Change GET method to POST method the following way:
Client side:
function Transfer(modelId) {
//alert(modelId);
$.ajax({
type: "POST",
url: "/Internet/Transfer",
data: {id: modelId},
success: function (responsedata) {
alert("ok");
window.location.href = responsedata.newUrl;
},
error: function (data) {
console.log("KO");
}
})
}
Controller side:
[HttpPost]
public ActionResult Transfer(long id)
{
*some actions*
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) });
}

How to show alert, popup or message if file is not created in MVC?

I have a action method:
public ActionResult Export(int? protocol, int? visitno)
{
SetViewBagItems();
if(protocl.hasValue)
{
// code create file
if (!string.IsNullOrEmpty(csvData))
{
return File(new System.Text.UTF8Encoding().GetBytes(csvData), "text/csv", "Report.csv");
}
else
{
// need to show something in ui like, not able to create file, or any popup or any alert....
}
}
return view();
}
So in the code as mentioned, I need to show something like an alert or message when able to create the file.
Now the behavior is:
if file gets created, it will get directly downloaded and wont reload the page.
if no file is created, then the entire page will refresh.
I need to show some message instead of that.
Same controller method is used for the page to load for the first time.
How can I achieve this?
Using $.ajax() to call that function in controller. Likes:
$.ajax({
url: "/controller/action",
type: "GET",
data: {protocol: protocol, visitno: visitno},
success: function(e) {
if(e != null)
{
//Alert
}
else {
//Alert
}
}
})
You can return a JSON result from your action method as:
return Json(new {
success = true,
status = "Failure"
}, JsonRequestBehavior.AllowGet);
The ajax method from where the action method is called, check for the return status and show the error or success message in the dialog box or through alert:
$.ajax({
type: "POST",
url: "/Controller/Action",
data: { "ID": $('#id').val() },
success: function (data) {
if (data.status == "Failure")
{
$('#dialog-Add-Success').dialog({
modal: true,
opacity: 1,
buttons: {
Ok: function () {
$(this).dialog('close');
}
},
})
}

Categories