Formcollection input values are empty in controller after ajax call - c#

I faced a problem with IE and FF; my application is working with Google Chrome.
I am binding a model to a view in ASP.NET MVC
I have a table row inside a form(and some other controls). I replace the table row's content on a button click with ajax call. After ajax call, if I submit form as shown below, I can not get formcollection inputs from controller method. There is no problem when I submit form before ajax call.
The js code to update table row's content:
function reloadCriteriaTable(unitID, criteriaCode, icerikRowSpan, icerikOnay) {
$.ajax({
type: "GET",
url: 'ApproveParts/ReloadCriteria',
data: { contentID: $('[name="contentID"]').val(), unitID: unitID, criteriaCode: criteriaCode, selectedValue: $("#validator_" + criteriaCode).val(), icerikRowSpan: icerikRowSpan, icerikOnay: icerikOnay },
cache: false,
type: "POST",
success: function (data, textStatus, XMLHttpRequest) {
$('#tr_' + criteriaCode).replaceWith(data);
$('#continueBtn').on('click', function () {
$('#form_3').submit();
return false;
});
},
error: function (xhr, status, error) {
alert(xhr + ' ' + status + " : " + error);
}
});
}
Onclick function:
$(document).on("click", ".btnSubmitCriteria", function () {
$('#form_3').submit();
return false;
});
Controller method:
[HttpPost]
public ActionResult CourseCriteriaApprovment(FormCollection collection)
{
}

To begin with why you have mentioned both type "GET" and "POST" in your ajax call. Use "POST" only.
Try this
$.ajax({
type: 'POST',
url: '/ApproveParts/ReloadCriteria',
dataType: 'json',
contentType: 'application/json',
data : return JSON.stringify({
contentID: $('[name="contentID"]').val(),
unitID: unitID,
criteriaCode: criteriaCode,
selectedValue: $("#validator_" + criteriaCode).val(),
icerikRowSpan: icerikRowSpan,
icerikOnay: icerikOnay
});
});
In your controller action accept a class instead of FormCollection. Where the class has all properties defined same as the ones you are sending in your ajax call.

Related

How to call codebehind method from Jquery after autocomplete selection

I have a autocomplete text box as and when the user types the city names are prompted. Once the user selects city name the selected value is retrieved using the following code:
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now I need to pass the selected value and call method in aspx.cs (code-behind) to retrieve further details of selected city.
How can I call a method from JQuery can somebody guide me towards that
You must call ajax in autocompleteselect like this
$('#txtName').on('autocompleteselect', function (e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({url: "aspx.cs",data:{value:ui.item.value}, success: function(result){
//response from server
}});
});
Server Side changes
You need to mark that method with WebMethod attribute to call it from the client side or you need to create a web service.
[WebMethod]
public static yourObject GetCityDetails(string cityId)//name this method as per your needs.
{
//Do whatever you want.
return yourObject; //it can also be in JSON format.
}
Client Side changes
Make an ajax call to the method from the client side.
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "yourpage.aspx/GetCityDetails", //same method name here.
data: { cityId: this.value },
success: function(result) {
//do whatever you want with server side data here.
}
});
});
You Can use Web Method
function GetDetails(cityId) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetDetails',
data: {"cityId":cityId},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (e) {
console.log(e);
}
});
}
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
GetDetails(ui.item.value);
});
in your aspx page
[WebMethod] //Default.aspx.cs
public static void GetDetails(cityId)
{
//Your Logic
}
Use $.Ajax to send the selected value to the server (code-behind) and get the response:
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "your-page.aspx/GetCityDetails",
data: { Name: this.value },
success: function(result) {
//Process the result from the code-behind.
}
});
});
Your code-behind must have a webmethod named GetCityDetails that accepts the name parameter and returns a city object as JSON.
This is what solved my issue:
The following is the code in jquery part in .aspx
function SetCityName(cityName) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetCityDetails',
data: JSON.stringify({ cityName: cityName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("CityName:" + cityName + "\n\nRequest: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
This is the code in .aspx.cs
[WebMethod]
public static string GetCityDetails(string cityName)
{
MessageBox.Show(cityName);
return "success";
}
The trick part is using the following piece in JQuery. I have tried above alternatives provided but none worked apart from the below piece of code:
data: JSON.stringify({ cityName: cityName }),

ajax not working to call asp.net web method

I am calling asp.net web method in my ajax call. Web method looks like below
[WebMethod()]
public static int DropDownIndexChanged(string selectedText)
{
int a = 5; // This is just to test
return a;
}
And in my ajax call, i am sending selected value in a drop down, having id DropDown, as follows
$.ajax({
type: "POST",
url: "FindFines.aspx/DropDownIndexChanged",
data: { "selectedText":"+$("#DropDown option:selected").text()+"},
success: function (data) {
alert("Success");
}
});
But function is not being called. Please guide me the right way to do it. Thanks.
I think your problem is "+$("#DropDown option:selected").text()+"
var value = $("#DropDown option:selected").text();
$.ajax({
type: "POST",
url: "FindFines.aspx/DropDownIndexChanged",
data: { "selectedText": value },
success: function (data) {
alert("Success");
}
});
Please Change
[WebMethod()]
to
[WebMethod]
and
data: { "selectedText":"+$("#DropDown option:selected").text()+"}
to
data: '{selectedText: "' + $("#DropDown option:selected").text() + '" }'

MVC posting form and extra param to an MVC controller using Ajax

I need to find a way to post a serialized form and an extra param to controller via ajax request. I can use serialize() on the form, or just send object with params, but cannot send both. How would I accomplish this?
For example I want my controller params to be as follows:
myaction(int siteID, Model model).
Pass what ever extra parameters you want along with form data as follows:
$.ajax({ type: 'POST',
url: "/MyController/Process",
data: $("form").serialize() + '&id=12345' ,
success: function () { alert("Successful"); },
dataType: "json"
});
Hope this helps..
You need to use something like this:
var dataToPost = $('#formID').serialize() + "&siteID=" + "23";
Now use this dataToPost variable in jquery ajax method like this:
$.ajax({
url: //url,
type: //'POST',
dataType: //'html',
async: true,
data: dataToPost,
cache: false,
}).success(function (response, status, xhr) {
}).fail(function (e) {
console.log(e);
});

What is wrong with this JQuery AJAX code

I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },

Jquery ajax autocomplete calling a method for data

$(function () {
$("#tbNominalAccounts").autocomplete({
source: function (request, response){
$.ajax({
url: "TestPage3.aspx/GetUserNominalAccounts",
type:"POST",
datatype:"json",
data :{ searchText : request.term},
success: function(data)
{
response(
$.map(data, function(item)
{
return { label: item.NominalAccount, value:item.NominalAccount, id:item.NominalAccount}
}))
}
})
}
});
});
Added breakpoints and it hits the ajax call but when i put a breakpoint on the method GetUserNominalAccounts it doesent even reach it!! Any ideas of why its not posting?!
I have a textbox with an ID of #tbNominalAccounts just for background information
Reformat your data like so:
pString = '{"searchText":"' + request.term + '"}';
$.ajax({
data: pString,
...
and your server side code should have been properly "decorated" to allow page access.
Thought I would add some code from a working sample using asp.net: you might need this converter for generic handling of the asp.net data:
dataType: "jsond",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
EDIT: And for the use of the return value:
focus: function(event, ui)
{
return false; // return "true" will put the value (label) from the selection in the field used to type
},
try putting a contentType in the ajaxRequest:
contentType: "application/json; charset=utf-8",
I've noticed that when using jQuery Ajax the default content Type application/x-www-form-urlencoded doesn't work well enough.

Categories

Resources