Getting Null for .val() - c#

I have inputs and selects. For some reason, some of them are giving me a null. Here is the code:
<script type="text/javascript">
$(function () {
$('#add').on('click', function () {
$('table').append('<tr>' +
'<td><button class=\'save\'>Save</button></td>' +
'<td><input name=\'name\' id=\'companyName\' /></td>' +
'<td><input name=\'currency\' id=\'currency\' /></td>' +
'<td><input name=\'ISOCode\' id=\'ISOCode\' /></td>' +
'<td><input name=\'CalcDeadLine\' id=\'CalcDeadLine\' /></td>' +
'<td><select name=\'mealAlgorithm\' id=\'mealAlgorithm\'><option value="True">Yes</option><option value="False">No</option></select></td>' +
'<td><input name=\'breakfast\' id=\'breakfast\' /></td>' +
'<td><input name=\'halfBoard\' id=\'halfBoard\' /></td>' +
'<td><input name=\'fullBoard\' id=\'fullBoard\' /></td>' +
'<td><input name=\'adminID\' id=\'adminID\' /></td>' +
'<td><input name=\'language\' id=\'language\' /></td>' +
'<td><input name=\'approvalcid\' id=\'cid\' /></td>' +
'<td><select name=\'useSMS\' id=\'useSMS\'><option value="True">Yes</option><option value="False">No</option></select></td>' +
'<td><select name=\'active\' id=\'active\'><option value="True">Yes</option><option value="False">No</option></select></td>');
$('#add').hide();
})
});
$(".save").live("click", function () {
var name = $("#companyName").val();
var currency = $("#currency").val();
var isoCode = $("#ISOCode").val();
var calcDeadLine = $("#CalcDeadLine").val();
var mealAlgorithm = $("#mealAlgorithm").val();
var noMeal = 111;
var breakfast = $("#breakfast").val();
var halfBoard = $("#halfBoard").val();
var fullBoard = $("#fullBoard").val();
var adminID = $("#adminID").val();
var language = $("#language").val();
var cid = $("#cid").val();
var useSms = $("#useSMS").val();
var active = $("#active").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("SaveCompany", "Admin")',
data: {
"CompanyName": name, "Currency": currency, "ISOCompanyCode": isoCode, "CalcDeadline": calcDeadLine,
"UseMealAlgorithm": mealAlgorithm, "NoMeal": noMeal, "Breakfast": breakfast, "HalfBoard": halfBoard,
"FullBoard": fullBoard, "AdminUserID": adminID, "ApprovalCulture": language, "ApprovalLcid": cid,
"UseSMS": useSms, "Active": active},
dataType: "json",
beforeSend: function () {
},
success: function (data) {
if (data.result == true) {
$("#GridCompany").html("Record has been saved!");
}
else {
alert("There is some error.");
}
}
})
})
In url of post everything is ok, it has true/false and every parameter with every value fulfilled.
In my controller I have
[HttpGet]
public JsonResult SaveCompany(string name, string currency, string isoCode, int calcDeadline, bool? mealAlgorithm,
int noMeal, int breakfast, int halfBoard, int fullBoard, string adminUserId, string approvalCulture,
int? approvalCid, bool? useSms, bool? active)
{
bool result = false;
try
{
result = _companyRepository.SaveCompany(name, currency, isoCode, calcDeadline, mealAlgorithm, noMeal,
breakfast, halfBoard, fullBoard, adminUserId, approvalCulture, approvalCid, useSms, active);
}
catch(Exception ex)
{
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
Nulls are isoCode, mealAlgorithm, approvalCid.

The problem is the wrong names of the fields.
In the AJAX you pass ISOCompanyCode but in the Action you're waiting for isoCode
The same is for the other two fields (you have different names). Use the same names and it'll fix your problem.

Related

Loading data into html table using ajax and SQL stored procedure

I have a stored procedure that selects all the fields in the table based on the date. I then created a method shown below to return the results as JSON.
[HttpGet]
public JsonResult GetResult()
{
MonthNameConverter converter = new MonthNameConverter();
string fullDate = converter.startOfMonth().ToShortDateString();
string[] split = fullDate.Split('/');
string date = "";
if(Convert.ToInt32(split[0]) < 10)
{
date = split[2] + "-0" + split[0];
}
else
{
date = split[2] + "-" + split[0];
}
var results = travelSOCC.GetLansingMileage(date).ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
However when I go to append the data to an HTML table I'm getting an unidentified result.
$(function LoadData() {
$("#LansingTable tbody tr").remove();
$.ajax({
type: 'GET',
url: '#Url.Action("GetResult")',
dataType: 'json',
data: JSON,
success: function (data) {
$.each(data, function (item) {
var rows = "<tr><td>" + item.TravelDate + "</td><td>" + item.TripType + "</td></tr>";
$("#LansingTable tbody").append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.resonseText);
alert("Message: " + r.Message);
}
})
});
Any help is greatly appreciated.
Please modify $.each(data, function(item) { as below:
$.each(data, function(idx, item) {
Please refer documentation here for more information.

Jquery returns value "undefined" .net core

I want to populate second dropdown from first one.
It all works but city names and values just returns "undefined". *Number of cities returns correct but the name and value are always "undefined". *
Controller:
[HttpPost]
public ActionResult getCityJson(string stateId)
{
int _stateid = Convert.ToInt32(stateId);
List<Cities> objcity = new List<Cities>();
objcity = _db.Cities.Where(m => m.stateID == _stateid).ToList();
SelectList obgcity = new SelectList(objcity, "CityID", "CityName", 0);
return Json(obgcity);
}
View Page:
$("#istateid").change(function () {
var id = $("#istateid").val();
$.ajax({
url: '#Url.Action("getCityJson", "Home")',
data: { stateId: id },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#icityid").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
I also tried Public JsonResult and return JsonResult and Public Selectlist and return SelectList but none of them worked.
And I also tried this:
$("#istateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("getCityJson", "Home")',
data: { stateId: $("#istateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your City--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
}) });
I recieve this in browser:
(TypeError: data[x] is undefined.)
$("#istateid").change(function () {
var id = $("#istateid").val();
$.ajax({
url: '/Home/getCityJson',
data: { stateId: id },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++)
{ markup += "<option value=" + data[x].CityID + ">" + data[x].CityName + "</option>"; }
$("#icityid").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
<option value="0">Select City</option>
<option value="undefined">undefined</option>
<option value="undefined">undefined</option>
<option value="undefined">undefined</option>
Solved:
items.push("<option value=" + this.value + ">" + this.text + "</option>");
Value and text camel cased.
Special thanks to #agua from mars
Other codes I tried:
$("#istateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("getCityJson", "Admin")',
data: { stateId: $("#istateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your Area--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
})
});
Controller:
[HttpPost]
public JsonResult getCityJson(string stateId, string selectCityId = null)
{
return Json(getCity(stateId, selectCityId));
}
public SelectList getCity(string stateId, string selectCityId = null)
{
IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(stateId))
{
int _stateId = Convert.ToInt32(stateId);
cityList = (from m in db.Cities where m.StateID == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.CityName, Value = m.CityID.ToString() });
}
return new SelectList(cityList, "Value", "Text", selectCityId);
}
try this:
success: function (data) {
var response=JSON.parse(data);
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < response.length; x++)
{ markup += "<option value=" + response[x].CityID + ">" + response[x].CityName + "</option>"; }
$("#icityid").html(markup).show();
},

html table jQuery json value pass

I want to pass value through jQuery Json.The problem is that while passing the value then,it have some problem,thats why it is not calling c# code.
This is the html table:
$(function ()
{
debugger
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm7.aspx/BindCategoryDatatable",
data: "{}",
dataType: "json",
success: function (dt) {
debugger;
for (var i = 0; i < dt.d.length; i++) {
$("#tblid > tbody").append("<tr><td> <input type='checkbox' class='chk' id=" + dt.d[i].projectid + " /></td><td>" + dt.d[i].projectname + "</td><td>" + dt.d[i].Name + "</td><td>" + dt.d[i].technology + "</td><td>" + dt.d[i].projectliveurl + "</td><td><input type='image' src=" + dt.d[i].StatusImage + " onclick='actvstatus(" + dt.d[i].projectid + ", " + dt.d[i].status + ")' alt='Submit' width='18' height='18'> </td><td>" + dt.d[i].DisplayOrder + "</td><td> <i class='ui-tooltip fa fa-pencil' onclick='btnQueryString_Click(" + dt.d[i].projectid + ")' style='font-size:22px;margin-left: 32px;'></i><i class='ui-tooltip fa fa-trash-o' onclick='deleteRecord(" + dt.d[i].projectid + ")' style='font-size: 22px;margin-left: 32px;color:red'></i> </tr>");
}
$("#tblid").DataTable();
},
error: function (result) {
alert("Error");
}
});
});
This is my c# Code:
[WebMethod]
public static List<mProjects> BindCategoryDatatable(int catid)
{
clsProjectBL objcategory = new clsProjectBL();
List<mProjects> modelCategory = new List<mProjects>();
DataTable dtCategory = new DataTable();
//dtCategory = objcategory.GetAllCategoryDetails("admin");
dtCategory = objcategory.GetAllProjectDetails("admin", catid);
if (dtCategory.Rows.Count > 0)
{
modelCategory = (from DataRow dr in dtCategory.Rows
select new mProjects()
{
projectid = Convert.ToInt32(dr["projectid"]),
CategoryID = Convert.ToInt32(dr["CategoryID"]),
projectname = dr["projectname"].ToString(),
Name = dr["Name"].ToString(),
technology = dr["technology"].ToString(),
projectliveurl = dr["projectliveurl"].ToString(),
DisplayOrder = Convert.ToInt32(dr["DisplayOrder"]),
status = Convert.ToBoolean(dr["status"]),
StatusImage = dr["StatusImage"].ToString(),
//Deleted = Convert.ToBoolean(dr["Deleted"])
}).ToList();
}
return modelCategory;
}
The value is not pass through webmethod...
Your back-end required a parameter catid so you have to pass catid to AJAX call as #BenG and #palash answer with data attribute.
data: { catid: 1 }
Or you pass it to the url with format
url: "WebForm7.aspx/BindCategoryDatatable?catid=" + YOUR_ID.
Otherwise, it will not be worked because BindCategoryDatatable return an empty list.

When i try send data from server to client nothing happened

Nothing happaned when i try do this in release mode but in debug mode all work fine - why???
When i adding button and outputing data by clicking this buton.My inner links in my list rows work fine also ( http://clip2net.com/s/2AG04 ).And only on $(document).ready(function () { event this doesn't want to work...
On client i have:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Index", "Product")',
cache: false,
type: 'GET',
dataType: 'json',
proccessData: false,
contentType: 'application/json; charset=utf-8'
});
On server i have this:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
//Отправляем на клиент данные
_senderHub.SendMessage();
return null;
}
return View();
}
Also on server:(SignalR)
readonly ManagerDB _managerDB = new ManagerDB();
public void SendMessage()
{
IEnumerable<ProductModels> list = _managerDB.GetListOfProduct1();
var listToClient = new List<ProductModels>();
foreach (var prod in list)
{
listToClient.Add(new ProductModels
{
Id = prod.Id,
Name = prod.Name,
LockType = prod.LockType,
LockTime = prod.LockTime,
LockUser = prod.LockUser,
TimeStampF = prod.TimeStampF
});
}
var anonimProduct = listToClient;
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SenderHub>();
context.Clients.AddListRows(anonimProduct);
}
On client(SignalR) trying catch this data:
$(function () {
var senderHub = $.connection.senderHub;
senderHub.AddListRows = function (data) {
var dataFromServer = data;
var listOfData = "";
for (var i = 0; i < dataFromServer.length; i++) {
$("#ListOfProductsTableBody").html(null);
var userId = '';
if (dataFromServer[i].LockUser != null) {
userId = dataFromServer[i].LockUser;
}
listOfData += ("<tr><td>" + dataFromServer[i].Id + "</td><td>" + dataFromServer[i].Name + "</td><td>" + userId + "</td><td>" + dataFromServer[i].LockType + "</td>" + "<td id=\"ModifyBlock\"><a id=\"Detail\" href=\"#\" alt=" + dataFromServer[i].Id + " >Детально</a>|<a id=\"Delete\" href=\"#\" alt=" + dataFromServer[i].Id + " >Удалить</a>|<a id=\"Edit\" href=\"#\" class=\"" + dataFromServer[i].LockTime + "\" alt=" + dataFromServer[i].Id + " >Редактировать</a></td></td></tr>");
}
$("#ListOfProductsTableBody").append(listOfData);
};
$.connection.hub.start();
});
emphasized text
See David Fowler's response to my question. Looks like you have the same issue.
Server to client messages not going through with SignalR in ASP.NET MVC 4

how to fetch return values between jquery functions and post ajax jquery request to webservice

I have the following code where the function codeaddress geocodes the text feild value and returns geocoded value , geocoded value is stored in variable example ,how will i return the variable v2 to the function call and post to asmx webservice.
<script type="text/javascript">
$(document).ready(function() {
$('#SubmitForm').submit(function() {
var geocoder;
var map;
function codeAddress(state) {
var address = document.getElementById("state").value;
geocoder.geocode( { 'address': state}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var v2=results[0].geometry.location;
alert(example);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
return v2;
});
var businessname = ($("#businessname").val());
var keyword = ($("#keyword").val());
var description = ($("#textarea").val());
var zipcode = ($("#zipcode").val());
var streetno = ($("#streetno").val());
var streetname = ($("#streetname").val());
var state = $('#state :selected').text();
var telephone = ($("#telephone").val());
var email = ($("#email").val());
var username = ($("#username").val());
var password = ($("#pass").val());
var repassword = ($("#pass1").val());
//data: "{'businessname':" + businessname + "'keyword':" + keyword + "}",
alert(state);
var v2=codeAddress(state);
alert(example);
var jsonobject = "{\"businessname\":\"" + businessname + "\",\"keyword\":\"" + keyword + "\",\"description\":\"" + description + "\",\"zipcode\":\"" + zipcode + "\",\"streetno\":\"" + streetno + "\",\"streetname\":\"" + streetname + "\",\"state\":\"" + state + "\",\"telephone\":\"" + telephone + "\",\"email\":\"" + email + "\",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"repassword\":\"" + repassword + "\"}";
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
});
function ajaxCallFailed(error) {
alert("error");
}
function ajaxCallSucceed(response) {
if (response.d == true) {
alert(" sucessfully saved to database");
}
else {
alert("not saved to database");
}
}
});
</script>
You call the codeAddress method with a callback. Inside codeAddress when you get value of v2, call the callback function passing it v2.
codeAddress(state,
function(v2) {
var jsonobject = "{\"businessname\":\"" + businessname/*.. use v2 in buiding jsonobject..*/;
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
}
);
function codeAddress(state, callback) {
var address = document.getElementById("state").value;
geocoder.geocode(...);
// ...
var v2=results[0].geometry.location;
callback(v2);
}

Categories

Resources