MVC controller's method not returning view - c#

I tried many ways and it's still not working... I'm calling controller's method with ajax call. Thanks to answer to my previous question it's working fine, I have data that I wanted to send from view in controller (in CreateIncident method). Problem is that controller should render new view and redirect to it, but it's not happening. For now I just want to see new view, nothing else, I'll deal with recieved data later. Any idea why is this happening? Is this because I'm calling method with ajax and not by e.g. simple Url.AcionLink?
Ajax call to method:
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress) + JSON.stringify(location)
$.ajax({
type: "POST",
url: "Incidents/CreateIncident",
dataType: "text",
data: {JsonStr : data}
})
}
Controller:
public ActionResult Create()
{
Incident newIncident = new Incident();
newIncident.AddDate = DateTime.Today.Date;
newIncident.DateOfIncident = DateTime.Today.Date;
newIncident.TimeOfIncident = DateTime.Today.TimeOfDay;
return this.View(newIncident);
}
[HttpPost]
public ActionResult CreateIncident(string JsonStr)
{
// RedirectToAction("Create"); //none of this three is working
// return View("Create");
return Redirect("Create");
}
No matter if I'm trying to access CreateIncident or Create the method is called, but there's no redirect to /Incidents/Create (I'm calling from Home/Index). Any ideas why? I would like to redirect to Create.cshtml straight from CreateIncident so I wouldn't have to pass data between methods, but any solution will do fine.

The redirect in that case has to be done through you AJAX call. Call your action method and do your logic, then redirect on success.
$.ajax({
type: "POST",
url: "Incidents/CreateIncident",
dataType: "text",
data: {JsonStr : data} ,
success: function (data) {
window.location.href = "Incidents/Create";
}
})

try:
url:"../Incidents/CreateIncident"
put in $ajax call error handling and see the error, it will help you
$.ajax({
type: "POST",
url: "Incidents/CreateIncident",
dataType: "text",
data: {JsonStr : data},
success: function(result){
// Do stuff
},
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
});

Use the view's full path instead of its name.
return View("/Incidents/Create");

Yes redirecting page in success event of ajax call is the only solution, as you are making ajax call not submitting a form. Browser redirects automatically after post only if you are posting a form.
However you can use following code if you don't want to redirect it in
success event.
function postData(url, allData){
form = document.createElement('form');
for(data in allData)
{
var input = document.createElement('input');
input.type = 'text';
input.name = data;
input.value = allData[data].toString();
form.appendChild(input);
}
form.method = 'post';
form.action = url;
form.submit();
}
and use this function like this :
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress) + JSON.stringify(location);
postData('/Incidents/CreateIncident', {JsonStr : data})
}
warning : haven't tested :).

Related

Cannot retrieve data from JsonResult in C# and ASP.NET MVC

I'm working on an ASP.NET MVC C# app and need to recover an object (modelview) when a specific button is clicked in the view. I managed to send the value to the JsonResult controller but I don't get back anything from it.
This is the code from the button in my razor view:
$("#btn-buscar").click(function (e) {
$.ajax({
type: "POST",
url: '#Url.Action(actionName: "BISSS_Modificacion", controllerName: "Home")',
datatype: "Json",
//contentType: "application/json; charset=utf-8",
data: { ISSS: $("#idISSSBuscar").val()},
success: function (data) {
alert(data);
alert("todo bien " + data.Nombres);
}
});
});
and this is the JsonResult controller, it works since it retrieves the info
public JsonResult BISSS_Modificacion(string ISSS)
{
Entity BusquedaEmpleado = new Entity();
// here I retrieve the info from a Web API
if (respuestaBusqueda.respuesta)
{
BusquedaEmpleado.NombreM = respuestaBusqueda.nombres;
BusquedaEmpleado.ApellidoM = respuestaBusqueda.apellidos;
BusquedaEmpleado.DUIM = respuestaBusqueda.dui;
BusquedaEmpleado.ISSSM = respuestaBusqueda.numero_isss;
BusquedaEmpleado.CargoM = respuestaBusqueda.cargo_participante;
BusquedaEmpleado.SexoM = respuestaBusqueda.genero;
BusquedaEmpleado.NivelM = respuestaBusqueda.nivel_puesto;
BusquedaEmpleado.grupoM = Convert.ToInt32(respuestaBusqueda.grupo);
return Json(new { BusquedaEmpleado }, JsonRequestBehavior.AllowGet);
}
}
But when it comes to show the object in an alert window - the first alert in the click button code - this is what I get:
and if I what to show a specific value - the second alert in the click button code - this is what I get:
and if I use console.log to show the data, this is what I get:
Could you please tell me what am I doing wrong?
If I use alert(JSON.stringify(data)), I get this, which is the info I need so it looks like I getting the proper info (there are some null values but its ok):
and as you can see the prop for Apellido is ApellidoM but if I want to show that value in an alert window still got undefined -alert("todo bien " + JSON.stringify(data.ApellidoM));
Based on the result of the json stringify you posted, it looks like you just need to use the names of the properties that are actually on the JSON object.
alert("todo bien " + data.NombreM); // todo bien JOSE ANGER

Controller Action Not Found JSON and ASP.NET MVC

Hi I have this controller method
[HttpPost]
public JsonResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
var data = new
{
CalculatedBMI = CalculateModel.BMICalc,
CalculatedBMIMeaning = CalculateModel.BMIMeaning
};
return Json(data, JsonRequestBehavior.AllowGet);
}
And this is my JS functions:
$('#good').click(function () {
var request = new BMICalculation();
$.ajax({
url: "CalculateAndSaveToDB",
dataType: 'json',
contentType: "application/json",
type: "POST",
data: JSON.stringify(request), //Ahhh, much better
success: function (response) {
$("#result").text(response.result);
},
});
ShowBMI();
});
function ShowBMI() {
$.ajax({
type: "GET",
dataType: "json",
contentType: "application/json",
url: "CalculateAndSaveToDB",
success: function (data) {
var div = $('#ajaxDiv');
div.html("<br/> " + "<b>" + "Your BMI Calculations: " + "</b>");
printBMI(div, data);
}
});
};
When ShowBMI() is executed, Chrome says GET http://localhost:50279/BMICalculations/CalculateAndSaveToDB/0 404 (Not Found)
The POST works as it saves to the database etc but the GET doesn't? Is there any reason for this? As you can see the URLs are exactly the same in each JS function so Im not sure why its found once nut not again the second time?
UPDATE:
After separating logic, the values appearing on the webpage are both null. See below for code changes
[HttpPost]
public JsonResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
CalculateAndSaveToDB(CalculateModel.BMICalc.ToString(), CalculateModel.BMIMeaning.ToString());
return Json("", JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult CalculateAndSaveToDB(string o, string t)
{
var data = new
{
CalculatedBMI = o,
CalculatedBMIMeaning = t
};
return Json(data, JsonRequestBehavior.AllowGet);
}
That's because you've applied the [HttpPost] attribute :) That attribute renders the action available solely for POSTing and not GETing. You should move the logic that is relevant for GETing to an action with the same name but without the [HttpPost] attribute and keep the logic for handling POSTed data in the action marked with the [HttpPost] attribute.
Be advised that you should reconsider the names when separating logic into different methods, or else the names will be misleading.
Regarding your update
I would have the POST request handling action (your action marked with HttpPost) return an ActionResult which in essence would mean that the POST request handling action upon successfully handling your request would redirect the user to a confirmation page or somewhere else. Wherever's preferable really :)
Try to approach it logically, what would be the natural chain of events upon POSTing the data? What would you as a user expect to happen?
Regarding your GET action, that is because you are not sending in the parameters o and t, which you then immediately return. Since nothing happens to these parameters in your logic and they are not otherwise specified, they will contain null which is the default value for variables of type string. Are you not intending to retrieve data from the database, rather than supply two parameters only to immediately return them?

Ajax to MVC controller. Not passing parameters unless Ajax followed by alert

I have the strangest situation. I have two ajax POST. First I had problems passing the parameters to the controller but at some point I got them trough and with some debugging I figured out that I only get all of the values to the controller if my ajax definition is followed by an alert.
One of them:
$.ajax({
type: 'POST',
url: '/Contact/IntresseAnmälan/',
dataType: 'json',
data: {
Namn: $('#namn').val(),
Mail: $('#mail').val(),
Info: $('#meddelande').val(),
Telefon: $('#nr').val(),
IsEnkel: false,
PassId: function () {
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
return id;
},
Participanter: getParticipant(),
ParticipantMail: getParticipantMail()
},
traditional: true,
success: function (result) {
// window.location.href = '#Url.Action("IntresseAnmälan", "Contact")';
}
});
alert("Hur sparas dina uppgifter?");
Here are my Getters for name and mail. The form-elements(input type mail and text) theese are dynamicly added to the form if the user wants clicks a button two inputs are added. Then theese functions returns an array with the inputed values from the form.
function getParticipant() {
var p = [];
for (var i = 1; i <= participantCount; i++) {
var name = '#anNamn' + i;
p[i -1] = $(name).val()
}
return p;
}
function getParticipantMail() {
var p = [];
for (var i = 1; i <= participantCount; i++) {
p[i -1] = $('#anMail' + i).val();
}
return p;
}
And here is my controller. I've removed the body in the controller. It saves to the Db and send a verification mail to the admin.
[HttpPost]
public ActionResult IntresseAnmälan(BokningContainer bokning)
{
//Saves to Db and Send a verification mail to admin
}
If I exclude the alert after the ajax some parameters are passed, I think it's Namn and Mail, but most of them not passed. I'm quite puzzled.
Also, is ajax the only way to pass an object to a controller from jQuery?
Also, is ajax the only way to pass an object to a controller from
jQuery?
No, you can use a regular HTML Form to submit your data, you just have to conform to the expected object in the controller Action (should be decorated with HttpPostAttribute) - There is a Model-Binding process which attempting to bind the Request data to your domain object.
You don't need to pass every field's value using jQuery. Instead you can create a form whose data you want to post like :
<form id="frmTest">
... add input types here
</form>
and you can pass data of form using $('#frmTest').serialize() method to the controller
$.ajax({
type: "POST",
data: $('#frmTest').serialize(),
url: "url",
dataType: "json",
success: function (data) { alert('worked!'); },
error: function (data) {
alert('error');
}
});

POST and GET executing simultaneously in MVC 4

I am trying to edit a field after clicking an item from a table.
I added an on clcik event to every object in the table like this :
onclick="itemEdit(this)
And my javascript function looks something like :
function itemEdit(e) {
console.log($(e).attr("id"));
var itmId = $(e).attr("id");
$.ajax({
url: '#Url.Action("Index", "Scraping")',
data: {itemId: itmId},
type: 'POST',
success: function(data) {
alert(data);
}
});
}
And what I do in my Index method is to load the clicked item in a more detailed manner on the top of the page like this :
public ActionResult Index(string itemId)
{
if (itemId != null)
{
im.loadItem(itemId.ToString());
}
else
{
if (im.lstEditModel.Count == 0)
{
im.loadLists();
}
}
return RedirectToAction("Index");
}
The problem I am having is that whenever I click an item, the index method executes twice..and thus creating a mess. Any help?
I don't see an [HttpPost] mark on that method, but at the end of the method, you are redirecting to another Index action... you normally would return some sort of JSON data rather than return RedirectToAction("Index");... this statement would be doing what you are describing, calling your Get Action.
From MSDN:
Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action.
Try to stop event bubbling.
function itemEdit(e) {
e.stopPropagation();
console.log($(e).attr("id"));
var itmId = $(e).attr("id");
$.ajax({
url: '#Url.Action("Index", "Scraping")',
data: {itemId: itmId},
type: 'POST',
success: function(data) {
alert(data);
}
});
}
Please ignore this, by mistake I forgot to put href="#" when adding the onClick event causing the browser to reload my javascript code. I had typed href=""

Passing Array to Action from a $.post

I am having trouble passing my array via a $.post.
The Javascript
var privIDs = [1,2,4,5];
$.post("/Home/GrantPrivilegesToUser", { privilegeIDs: privIDs }, function (data) {
alert("Data Loaded: " + data.success);
});
The Action
public ActionResult GrantPrivilegesToUser(int[] privilegeIDs)
{
return Json(new {success=true});
}
The action sees privilegeIDs as null. Any ideas?
You need to set jQuery.ajaxSettings.traditional = true; for you jQuery ajax setting. In jQuery 1.4 they changed the way items are serialized in a form post.
please see:
http://forum.jquery.com/topic/nested-param-serialization
And:
How can I post an array of string to ASP.NET MVC Controller without a form?
I use JSON to pass data as a string using the JSON2 library: http://www.json.org/js.html
var privIDs = [1,2,3,4,5];
var data = JSON.stringify({privilegeIDs : privIDs});
$.POST("/Home/GrantPrivilegesToUser", data, function (data) {
alert("Data Loaded: " + data.success);
});
And the action would use the WebMethod type:
[WebMethod]
public object Entry_GetFormOptions(string privilegeIDs)
{
return new {success=true};
}
There are both built-in and 3rd party functions for parsing the received JSON to access the privilege IDs.
Let me know if this does or does not help.
This is what I ended up doing. Might be helpful to someone...
var privIDs = [1,2,4,5];
$.ajax({
type: "POST",
url: "/Home/UpdatePrivileges",
data: { privilegeIDs: privIDs },
traditional: true,
success: function (json) {
alert(json.success);
}
});
If you use .ajax instead of .post you can include traditional: true

Categories

Resources