I'm trying to take input from Users through a checkbox and store it in a table in my SQL DB, I've created all the link properly and my post AJAX call works well because I was able to receive information in my DB. The problem is the parameter received in my controller is receiving a null value which is storing a null value in my table, I know that my checkbox is pulling the right information because im printing it before hand but I feel like my AJAX setup may not be stringifying it properly.
$("#submitButton").click(function() {
var results = {};
$questions = $('#optionData');
for (i = 1; i < 6; i++) {
if ($questions.find('#option' + i).prop('checked')) {
results['option' + i] = $questions.find('#option' + i).val();
}
newResult = JSON.stringify(results)
};
console.log(newResult);
$.ajax({
url: "/Home/SaveData",
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: (newResult),
success: function(data) {
if (data == null) {
alert("Something went wrong");
}
},
failure: function(data) {
alert(data.dataText);
},
error: function(data) {
alert(data.dataText);
}
});
});
[HttpPost]
public ActionResult SaveData(string Options)
{
dataInsertion dataInsertion = new dataInsertion
{
// questionID = object.QuestionId,
options = Options,
// },
// companyID = object.companyID
};
try
{
if (ModelState.IsValid)
{
DB.dataInsertions.Add(dataInsertion);
DB.SaveChanges();
// RedirectToAction("Home");
}
}
catch (Exception e)
{
Console.WriteLine("error" + e);
}
return Json(new { sucess = "true" });
}
Related
I have a JQuery function that load some data from C# and update information on my view.
I must to load a large dataset and all works fine, but for some reason i must to load a dynamic list and elaborate its from JQuery.
The list is "listCasistiche" and when i load it from MVC the JQuery function goes in error.
How can i take this list?
The JQuery function is this:
var data = $('#jqxgrid').jqxGrid('getrowdata', rowindex);
var uf = new FormData();
uf.append("id", data.Id);
var url = "/Clienti/LoadSelezionato";
$.ajax({
type: "POST",
url: url,
dataType: 'json',
contentType: false,
processData: false,
data: uf,
error: function () {
// The function go in error
},
success: function (result) {
if (result != "error") {
result.listCasistiche.forEach(function (entry) {
alert(entry.IdCasistica);
});
ricaricaNeri();
$('#OwnLead').val(result.ownerLead);
$('#dataLead').datepicker('setDate', result.dataLead);
}
}
});
The MVC LoadSelezionato function is this. All other parameters are loaded well:
[HttpPost]
public ActionResult LoadSelezionato(FormCollection form)
{
int id = Convert.ToInt32(form["id"]);
try
{
Cliente clienteLead = conc.Clientes.FirstOrDefault(x => x.Id == id);
if (clienteLead != null)
{
var elemento = new
{
ownerLead = clienteLead.OwnerLead,
dataLead = clienteLead.DataLead,
listCasistiche = conc.CasisticheClientes.Where(x => x.IdCliente == id).ToList()
};
return Json(elemento, JsonRequestBehavior.AllowGet);
}
else
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
Thanks to all
I am doing ajax call in Asp.Net MVC with this code
$.ajax({
type: "GET",
url: '#Url.Action("GetAllFacts", "Home")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[0].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[0].Content + "'</div></div></div></div>");
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[1].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[1].Content + "'</div></div></div></div>");
},
error: function () {
alert("Error");
}
});
This hits to my Get Method GetAllFacts() with following codes
[HttpGet]
public JsonResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(allData_Facts, JsonRequestBehavior.AllowGet);
}
}
catch (Exception)
{
}
return Json("false", JsonRequestBehavior.AllowGet);
}
This is my code which returns list with 2 data properly, but after that it is not going to success method it alerts error as per Ajax error function.
Where I am wrong?
Try by
Remove assembly reference System.Web.Mvc out of your project.
Use nuget to install System.Web.Mvc for you project.
Verify Web.config to make sure it have System.Web.Mvc assembly.
Run to check.
Good luck!
ajax:
$.ajax({
type: "GET",
url: '/Home/GetAllFacts',
dataType: "json",
success: function (data) {
if (data.success) {
// connect to server successful and everything's ok
// access to server returned data: data.alldata
} else {
// connect to server successful but something went wrong
alert(data.ex); // throw exception message
}
},
error: function () {
// connect to server failure
}
});
controller:
[HttpGet]
public ActionResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(new { success = true, alldata = allData_Facts }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
return Json(new { success = false, ex = e.Message }, JsonRequestBehavior.AllowGet);
}
}
I'm trying to convert a List into a Json to send it to an Ajax Request, but when I recover only one register from the Database it works, but if I have more then one, the ajax returns an error.
Below is my code:
public ActionResult RecuperaLocalidadesPorUsuario(int usuarioId)
{
BpUsuario m = new BpUsuario();
IList<Localidade> states = m.ObterPorId(usuarioId).Localidades.ToList();
states.Add(m.ObterPorId(usuarioId).UsuaAreaPadrao);
var result = (from s in states.Where(x => x != null).Distinct().ToList()
select new { id = s.LocaCodigo, name = s.LocaNome}
).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Here is the Ajax call
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("RecuperaLocalidadesPorUsuario", "Usuario"))",
data: { "usuarioId": selectedItem },
contentType: 'json',
success: function (data) {
alert("entrou no success");
if (data.length == 0) {
ddlLocalidades.find('option').remove();
ddlLocalidades.append($('<option></option>').val("").html("O Usuário não tem localidades cadastradas"));
ddlLocalidades.attr("disabled", true);
} else {
ddlLocalidades.attr("disabled", false);
ddlLocalidades.find('option').remove();
ddlLocalidades.append($('<option></option>').val("").html("Todas"));
$.each(data, function (id, option) {
if (option.id == '#Request.Cookies.Get("UserAreaPadrao").Value') {
ddlLocalidades.append($('<option selected></option>').val(option.name).html(option.name));
} else {
ddlLocalidades.append($('<option></option>').val(option.name).html(option.name));
}
});
}
$('#ddlLocalidades').multiselect('rebuild');
},
error: function (data) {
alert("entrou no error");
}
});
I tried many links here at stackoverflow , but without any success, and I'm really stuck into this problem.
I have a function in c# that gets a budget and Id-s of ads and updates all the budgets of these ads to be with budget value of budget:
[HttpPost]
public ActionResult UpdateAdsBudgets(string budget, string[] Ids)
{
ServerResult serverResult = null;
try
{
int numOfSuccess = 0;
for (int i = 0; i < Ids.Length; i++)
{
serverResult = UpdateAdBudget(Ids[i]);
if (serverResult.ServerResultState == ServerResultState.SUCCESS)
{
numOfSuccess++;
}
}
}
}
I called this function in my js file:
$.ajax({
dataType: 'json',
type: "POST",
traditional: true,
url: "/AdsController/UpdateAdsBudgets",
data: { budget: budget, Ids: adsIds },
success: function (serverResult) {
},
error: function (exception) {
}
});
Is there an option to display a message with an info of the called function? I mean to: 2/5 ads were updated, where 2 is numOfSuccess (the variable of my c# file) and 5 is: adsIds.length.
I know I can do a lot of ajax calling (for each ad) and then count it in the succes, but is there an option that the function of c# will update online a variable in my js file? (assuming the variable: "numberOfSuccededAds").
any help appreciated!
Why not just return Json(YOR_DATA_YEAR) and handle it in success handler of your JavaScript ajax function.
public ActionResult UpdateAdsBudgets(string budget, string[] Ids)
{
ServerResult serverResult = null;
try
{
int numOfSuccess = 0;
for (int i = 0; i < Ids.Length; i++)
{
serverResult = UpdateAdBudget(Ids[i]);
if (serverResult.ServerResultState == ServerResultState.SUCCESS)
{
numOfSuccess++;
}
}
}
return Json(YOUR_DATA);
}
You can return a JsonResult from your controller like so:
[HttpPost]
public ActionResult UpdateAdsBudgets(string budget, string[] Ids)
{
ServerResult serverResult = null;
try
{
int numOfSuccess = 0;
for (int i = 0; i < Ids.Length; i++)
{
serverResult = UpdateAdBudget(Ids[i]);
if (serverResult.ServerResultState == ServerResultState.SUCCESS)
{
numOfSuccess++;
}
}
}
return Json(numOfSuccess);
}
You can then do an alert in your Javascript to inform the user.
$.ajax({
dataType: 'json',
type: "POST",
traditional: true,
url: "/AdsController/UpdateAdsBudgets",
data: { budget: budget, Ids: adsIds },
success: function (serverResult) {
alert(serverResult + "/" + adsIds.length + " ads were updated");
},
error: function (exception) {
} });
is there an option that the function of c# will update online a variable in my js file
No, your ASP.NET service knows absolutely nothing about the client your only option is to pass the information it needs back as part of the post e.g.
[HttpPost]
public ActionResult UpdateAdsBudgets(string budget, string[] Ids)
{
...
return Json(numOfSuccess);
}
Then in your success callback
success: function (serverResult) {
alert(serverResult+ '/' + adsIds.length + ' ads were updated');
}
I have a need to call a method on my controller to return a complex type using the JQuery.Ajax method.
function CallMethodTest(Id) {
//alert(Id);
$.ajax({
type: 'POST',
url: '/MyController/MyMethod',
dataType: "json",
contentType: "application/json; charset=utf-8",
//data: "{'Id': '" + Id + "'}",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
[System.Web.Services.WebMethod]
public string MyMethod()
{
return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
return "1"; // Works fine
}
As the code explains, if I return an integer (as a string) the return works and I alert "1", however, If I try and return any alpha characters I get the alerts shown in the comments of MyMethod.
From your code, it looks as though you are returning the value from your Controller url: "/MyController/MyMethod"
If you are returning the value from your controller, then get rid of the [System.Web.Services.WebMethod] code and replace it with this ActionResult
[HttpPost]
public ActionResult MyMethod(){
return Json("ABC");
}
Also, if you are ever going to call a method in your controller via GET then use
public ActionResult MyMethod(){
return Json("ABC", JsonRequestBehavior.AllowGet);
}
In View You use the following code,
function ItemCapacity() {
$.ajax({
type: "POST",
url: '#Url.Action("ItemCapacityList", "SalesDept")',
data: { 'itemCategoryId': itemCategoryIds },
dataType: 'json',
cache: false,
success: function (data) {
var capacityCounter = 0;
var capacitySelected = "";
for (var i = 0; i < rowsCount; i++) {
var tr = $("#gvSpareSetItemsDetails tbody tr:eq(" + i + ")");
var categoryId = $(tr).find('td:eq(5)').text();
var isSelectOrNot = $(tr).find('td:eq(1)').find('select');
if (isSelectOrNot.is('select')) {
$.map(data, function (item) {
if (categoryId == item.ItemCategoryID) {
isSelectOrNot.get(0).options[isSelectOrNot.get(0).options.length] = new Option(item.CapacityDescription, item.ItemCapacityID);
capacityCounter = capacityCounter + 1;
capacitySelected = item.ItemCapacityID;
}
});
if (capacityCounter == 1) {
isSelectOrNot.val(capacitySelected);
}
capacityCounter = 0;
capacitySelected = "";
}
}
},
error: function () { alert("Connection Failed. Please Try Again"); }
});
}
}
In the Controller Use the following Code,
public JsonResult ItemCapacityList(string itemCategoryId)
{
List<ItemCapacity> lsItemCapacity = new List<ItemCapacity>();
string[] itemCategory = itemCategoryId.Split('#');
int itemCategoryLength = itemCategory.Length, rowCount = 0;
string itemCategoryIds = string.Empty;
for (rowCount = 0; rowCount < itemCategoryLength; rowCount++)
{
itemCategoryIds += "'" + itemCategory[rowCount].Trim() + "',";
}
itemCategoryIds = itemCategoryIds.Remove(itemCategoryIds.Length - 1);
lsItemCapacity = salesDal.ReadItemCapacityByCategoryId(itemCategoryIds);
return new JsonResult { Data = lsItemCapacity };
}