C# & ASP.NET MVC : call a view with ajax call - c#

I want to call a view with an ajax call on my current view. The following is my Ajax call that calls a function of my controller.
$.ajax({
type: 'POST',
url: '#Url.Action("EditCertificateObservation", "Frühwarnsystem")',
data: {
serverName: '#Model[0].ServerName',
name: event.data.name,
thumbprint: event.data.thumbprint,
expiringDateStr: event.data.expiringDate,
isChecked: document.getElementById(store + event.data.index).checked,
model: data,
},
});
This code is my controller function that returns a view to load.
[HttpPost]
public ActionResult EditCertificateObservation(string serverName, string name, string thumbprint, string expiringDateStr, bool isChecked, string model)
{
var newModel = JsonConvert.DeserializeObject<List<Store>>(model);
var cert = new Certificate(serverName, name, thumbprint, expiringDateStr);
var server = new Server(serverName);
server.FetchIdByServerName();
if (isChecked)
{
cert.AddToObservation(server.Id);
}
else
{
cert.DeleteFromObservation();
}
return View("Index");
}
To know for you: I call the ajax call with a checkbox on my view, which is dynamically generated. If I debug the controller function get called and runs but the browser doesn't load the view I return.
If you need more information, just ask here.
Thank you for your help

If you want to open a view with after Ajax request than you just have to wait for the response of your controller then you can use success, but you can also use failure or error depend on your need, so your Ajax will be like this:
$.ajax({
type: 'POST',
url: '#Url.Action("EditCertificateObservation", "Frühwarnsystem")',
data: {
serverName: '#Model[0].ServerName',
name: event.data.name,
thumbprint: event.data.thumbprint,
expiringDateStr: event.data.expiringDate,
isChecked: document.getElementById(store + event.data.index).checked,
model: data,
},
success: function (response) {
alert(response.message);
window.location.href = "/Frühwarnsystem/Index";
// or with some parameter
window.location.href ="/Frühwarnsystem/Index?id=" + response.counter;
// or if you prefer with helper ...
window.location.href = '#Url.Action("Frühwarnsystem","Index")';
},
failure: function (response) { alert("failure"); },
error: function (response) { alert("error"); }
});
And to be a little more useful, your controller can send a Json response with some parameter for example, as follow:
[HttpPost]
public JsonResult EditCertificateObservation(string serverName, string name, string thumbprint, string expiringDateStr, bool isChecked, string model)
{
var newModel = JsonConvert.DeserializeObject<List<Store>>(model);
var cert = new Certificate(serverName, name, thumbprint, expiringDateStr);
var server = new Server(serverName);
server.FetchIdByServerName();
if (isChecked)
{
cert.AddToObservation(server.Id);
}
else
{
cert.DeleteFromObservation();
}
// Do some condition here to send an answer ...
string message = "";
int counter = 0;
var response = new { counter, message };
return Json(response);
}

You are calling an ajax POST HTTP request. It means you can download the result of the call and assign it into a javascript variable. This result will not be displayed in the browser as a page. Take a look at examples of $.post here.

Related

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

ajax request to razor page using handler

I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});

Cant do redirect (ASP.NET MVC)

I need to do redirect to controller
Here is my controller
[HttpPost]
public ActionResult Index(string question1, string question2, string question3, string question4, string question5, string question6, string question7, string question8, string question9, string question10, Int32 id)
{
QuestionBlock question = new QuestionBlock
{
Question1 = question1,
Question2 = question2,
Question3 = question3,
Question4 = question4,
Question5 = question5,
Question6 = question6,
Question7 = question7,
Question8 = question8,
Question9 = question9,
Question10 = question10,
Interview_Id = id,
};
//TempData["id"] = id;
db.QuestionBlocks.Add(question);
db.SaveChanges();
return Json(new { Result = "Success", Message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
I try to do it like this
return RedirectToAction("Index", "Questions", new { id = id });
I have this AJAX call in my View. Maybe trouble in it?
<script>
$('.click').on('click', function () {
$('.content').toggle();
});
var counter = 0;
$(document).ready(function () {
$('#save').click(function () {
save();
});
});
function save()
{
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
question1: $('#Question1').val(),
question2: $('#Question2').val(),
question3: $('#Question3').val(),
question4: $('#Question4').val(),
question5: $('#Question5').val(),
question6: $('#Question6').val(),
question7: $('#Question7').val(),
question8: $('#Question8').val(),
question9: $('#Question9').val(),
question10: $('#Question10').val(),
},
url: '#Url.Action("Index", "Questions")',
success: function (da) {
if (da.Result === "Success") {
alert('Вопросы сохранены');
} else {
alert( 'Error'+ da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
</script>
But redirection not works. Where is my trouble?
Maybe I need to do it not in controller?
Thank's for help
Your current code is returning a JSON response with 2 properties and your main view code is making an ajax call to this action method. So the JSON response returned from the action method will be handled in the success handler of your ajax call. It will not do a redirect unless you explicitly do so.
Even if you replace the return Json with return RedirectToAction, It does not makes sense to use it with the Ajax call. The whole idea of ajaxifying the page is to avoid the traditional page submit - reload experience and replace it with partial page upload behavior (better user experience)
If you absolutely want to redirect to another page, you can do that in the success event handler. But like i mentioned earlier, it does not makes sense to do an ajax post then. Do a normal form post!
if (da.Result === "Success") {
window.location.href="Give the new Url you want to navigate to here";
}
You can use the UrlHelper class to generate the correct url to the other action method and send that as part of your JSON response.
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Index", "Questions",new { id= id});
return Json(new { Result = "Success", Message = "Saved Successfully",RedirectUrl=url });
Now in your ajax call , read the RedirectUrl property
if (da.Result === "Success") {
window.location.href=da.RedirectUrl;
}
Have you tried just like this without writing Questions.:
return RedirectToAction("Index", new { id = yourvalue });
EDIT:
Otherwise you can try this:
return RedirectToAction( "Index", new RouteValueDictionary(
new { controller = controllerName, action = "Index", id = id } ) );

MVC Jquery POST data, redirect to url from ActionResult

I am currently working with mvc. I have a page with more than one button on, which does complicate things a little. However the button I am using calls a jquery function to post data to the controller. This works as expected and data reaches the action and the action does everything expected except redirect.
The function posts data to the controller, or allows the controller to see the values and build up a url to then redirect to. However the redirect doesnt work, and the function calls a success function as expected. If I put the data return into an alert the code for the page is returned in the alert window not the url.
Here is the code:
<input type="submit" value="Assign" name="Assign" onclick="doRedirect()" />
function doRedirect() {
var action = '#Url.Action("Redirect")';
//alert(action);
var opt = {
type: "POST",
data: {
Team: $('#Team option:selected').val()
},
url: action,
success: RedirectSuccess
};
jQuery.ajax(opt);
}
function RedirectSuccess(data) {
if (data != undefined) {
data;
}
}
public ActionResult Redirect(string Team)
{
var hostName = "http://localhost/test/testpage.aspx?";
var team = "&Team=" + Team;
var filterUrl = Team;
return Redirect(filterUrl);**//this doesnt work**
}
Instead of sending back a redirect result from the action, try sending back the URL you want to redirect to. On the client side, you read the response of the request, and do the redirect by setting window.location.href to the URL you get back from the server.
In your action, you could return the URL as JSON for instance:
return Json(new { url: filterUrl });
And in your success callback, you do this to redirect:
if (data !== undefined && data.url !== undefined) {
window.location.href = data.url;
}
This is what I did instead.
public string Redirect(string Team)
{
var hostName = "http://localhost/test/testpage.aspx?";
var team = "&Team=" + Team;
var filterUrl = hostname + Team;
return filterUrl;
}
function RedirectSuccess(data) {
if (data != undefined) {
window.location = data;
}
}
and on my search success

Categories