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

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

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

MVC controller's method not returning view

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 :).

How to obtain checked checkbox values on the serverside in c# from an ajax Http POST using web forms (not MVC)?

Here's my ajax call:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());
console.log($(this).prop("name") + "=" + $(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default",
type: "POST",
dataType: "json",
data: { filterValues: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
And my server side code:
public partial class tools_oppy_Default : System.Web.UI.Page
{
...
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
string checkedBoxes = Request["filterValues"];
testLabel.Text = checkedBoxes;
}
I'm just trying to obtain the post URL with the appropriate checked values so I can parse it on the server. However, I'm having trouble obtaining the URL. The string checkedBoxes is supposed to hold a query string like name=value&name=value&name.... but when I test it, the testLabel doesn't show anything. I'm using web forms app, not MVC. Also, I'm new to ajax and their behavior. Thanks.
First, I assume that the url in you JQuery call is valid as there is not aspx extension their.
Second, It looks like what you need to do is create a web method and call it from JQuery for example the following is a web method that accept string
[WebMethod]
public static string GetData(String input)
{
return DateTime.Now.ToString();
}
and you can call it using the same way with your current code just update the url parameter to include the method name
url: "PageName.aspx/MethodName",
for more details about web methods and their union with JQuery please check this article
Edited The following is complete sample
The web method should look like the following one
[WebMethod]
public static string GetData(string filterValues)
{
return filterValues; //This should be updated to return whatever value you need
}
The client side part of calling the web method should look like the following
$.ajax({
url: "/Default/GetData",
type: "POST",
contentType: "application/json; charset=utf-8", //I have added this as "contentType" parameter represents the type of data inside the request meanwhile the "data" parameter describes the data inside the response
data: "{ filterValues:\"" + filterCheckboxes + "\"}", //Note that I have updated the string here also set the name of the parameter similar to the input of the webmethod
dataType: "json",
success: function (result) {
alert(result.d);//You should access the data using the ".d"
}
});
One last thing, If you are using asp.net permanent routing the above code will not work and you should disable it by updating the file "App_Code/RouteConfig.cs" From
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
And remember to clear browser cache after the above update

jQuery keeps failing when trying to call a controller

I am trying to call a controller action in ASP.Net MVC 5 from a jQuery ajax method. Everything seems to be in place and correct, however my ajax keeps failing. The error return keeps presenting itself and my page does not refresh. However, my controller does get hit. If I set a break point in the C# code under the specific action I am trying to access all goes according to plan.
Yet still the ajax returns an error and the page is never redirected to.
Here is my jQuery script
$(document).ready(function () {
$('.searchbox').on('search', function () {
if ($(this).val() == undefined || $(this).val() == '') {
$.ajax({
type: 'GET',
contentType: 'application/json',
dataType: 'json',
url: '#Url.Action("Index","Company")',
error: function () { alert('error'); }
});
}
});
});
Any suggestions? I can post more code if need be. I am using a search input type and this fires when I clear the search box.
Thanks for any help I get!
Here is the controller
[HttpGet]
public ActionResult Index(Int32? resultsPerPage, Int32? startingIndex, Int32? currentPage, String searchExpression)
{
List<ProspectModel> prospects = ProspectManager.LoadProspects(searchExpression);
resultsPerPage = resultsPerPage ?? 25;
startingIndex = startingIndex ?? 0;
currentPage = currentPage ?? 1;
if(!String.IsNullOrWhiteSpace(searchExpression))
{
ViewBag.Pages = 0;
ViewBag.TotalRecords = prospects.Count;
ViewBag.CurrentIndex = 0;
ViewBag.ResultsPerPage = resultsPerPage;
ViewBag.CurrentPage = 1;
ViewBag.LastPageStartingIndex = 1;
ViewBag.SearchExpression = searchExpression;
return View(prospects);
}
List<ProspectModel> model = prospects.GetRange((Int32)startingIndex, (Int32)resultsPerPage);
ViewBag.TotalRecords = prospects.Count;
ViewBag.Pages = (prospects.Count / resultsPerPage) + ((prospects.Count / resultsPerPage) % 2 != 0 ? 1 : 0);
ViewBag.CurrentIndex = startingIndex + resultsPerPage;
ViewBag.ResultsPerPage = resultsPerPage;
ViewBag.CurrentPage = currentPage;
ViewBag.LastPageStartingIndex = ((prospects.Count / resultsPerPage) % 2 == 0 ? prospects.Count - resultsPerPage : prospects.Count - ((prospects.Count / resultsPerPage) % 25));
ViewBag.SearchExpression = null;
return View(model);
}
In MVC GET ajax requests are blocked by default , you have to change it to Post , or allow GET
return Json("string or model here" ,JsonRequestBehavior.AllowGet);
try changing your jQuery to type 'POST' , just once and see if that fixes it. If it does then you can try the code I provided.
You are getting a 404 because your Action Index does not have a path that accepts 0 parameters , you have all your int's set to nullable , but you have to atleast provide that parameter searchExpression.
Try hardcoding the url instead of Razor, and try passing it sometype of string.
$.ajax({
type: 'GET',
contentType: 'application/json',
data: { searchExpression : "test" },
dataType: 'json',
url: '/Company/Index',
success: function(data) { alert('success'); },
error: function () { alert('error'); }
});
the other answer is probably also a lot of help , I was going to reccommend also removing the contentType and dataType, they are not needed , and jQuery does a very good job at making an educated guess as to what the types are supposed to be
$.ajax({
type: 'GET',
data: { searchExpression : "test" },
url: '/Company/Index',
success: function(data) { alert('success'); },
error: function () { alert('error'); }
});
If I read your initial post correctly, then you're saying that you get all the way to and past the return View() call in your controller, but your jQuery AJAX call says there was an error.
Your View is probably HTML, is that right to say? If so, because in your AJAX call you've specified that you're expecting JSON, jQuery is trying to parse the response as JSON before giving it to you. This could be the root cause of your error.
In the controller, replace the return View with:
return JSON(new { Test = "Hello!" }, JsonRequestBehavior.AllowGet);
And in a success handler to your AJAX call:
success: function(data) { alert(data.Test); }
If that works, then you need to either specify in your AJAX that you're going to be receiving HTML, or return your model in JSON from MVC and handle it in the success function, depending on what you are trying to achieve.
If you want to return HTML to your ajax call, then try this sample I just toyed with:
Controller
public class HomeController : Controller
{
public ActionResult Search(
Int32? resultsPerPage,
Int32? startingIndex,
Int32? currentPage,
String searchExpression)
{
return View();
}
}
JavaScript
$.ajax({
type: 'GET',
contentType: 'application/json',
dataType: 'html',
url: '#Url.Action("Search", "Home")',
success : function(data){ alert(data);},
error: function () { alert('error'); }
});
The key is the dataType. You need to set that to the type of content you expect to be returned from the ajax call, in your case you want to return HTML. Not setting that correctly will result in the error function being called.

Passing a parameter from JavaScript to a controller

I am trying to pass a string value to a create item dialog, and am not sure on how to do it.
This is the code in my view:
JavaScript:
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}
View:
<td>#route</td>
<td>
Add
</td>
Controller:
public ActionResult Create(string routeName = "")
{
PopulateRouteInfoViewBag();
var newRoute = new RouteInformation();
newRoute.Name = routeName;
return View(newRoute);
}
I'm trying to take the value in #route and pass it over to the Create controller to have my dialog pop up with the passed in string value.
Use the ActionLink html helper method and pass the route variable like this.
#{
string route="somevaluehere";
}
#Html.ActionLink("Add","Create","YourControllerName",
new { routeName=route},new {#id="addLnk"})
Now handle the click event
$(function(){
$("#addLnk").click(function(e){
e.preventDefault(); //prevent normal link click behaviour
var _this=$(this);
//do your ajax call now
$.ajax({
url: _this.attr("href"),
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = 'someValidUrlHere'
else
$.facybox(data);
}
});
});
});
Also, You may consider building the path to the new page(action method) and return that as part of your JSON result and let the client read it from the JSON.
instead of appending the route variable value to the querystring, you may consider it as the part of message body.
There are two options. 1, use Url.Action("controllerName", "actionName", new {routeName = "your route name here"}) or 2, use the data property of the object passed into $.ajax.
For 2 your javascript would look something like
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
data: {
route: "your data here"
}
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}

Categories

Resources