MVC and JQuery Load parameter List - c#

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

Related

I am trying an async ajax call in MVC. The daata is not sent to server

The function sends data to server. The billItem stores the detail level entitity data. I am using MVC and i have Create method in controller class HomeController. I have two classes Bill and BillItem that is master and detail respectivelly.
$('#submit').click(function () {
var isValidItem = true;
if ($('#BillNo').val() == 0) {
isValidItem = false;
$('#BillNo').siblings('span.error').css('visibility', 'visible');
}
else {
$('#BillNo').siblings('span.error').css('visibility', 'hidden');
}
if ($('#CustomerName').val() == '') {
isValidItem = false;
$('#CustomerName').siblings('span.error').css('visibility', 'visible');
}
else {
$('#CustomerName').siblings('span.error').css('visibility', 'hidden');
}
if ($('#Address').val() == '') {
isValidItem = false;
$('#Address').siblings('span.error').css('visibility', 'visible');
}
else {
$('#Address').siblings('span.error').css('visibility', 'hidden');
}
if (isValidItem) {
alert(billItem);
var data = {
BillNo: $('#txtBillNo').val(),
CustomerName: $('#txtCustomerName').val(),
Address: $('#txtAddress').val(),
Gender: $('input[name="Gender"]:checked').val(),
BillDetail: billItem
}
//$(this).val() = "Please wait...";
$ajax({
url: '/Home/Create',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
if (d.status == true) {
alert("Successfully saved.");
billItem = [];
$('#txtBillNo').val('');
$('#txtCustomerName').val('');
$('#txtAddress').val('');
}
else {
alert("Error saving data.");
}
$('#submit').val('Save');
},
error: function () {
alert("Error saving data.");
}
});
}
});
Your Ajax call should look like this:
if (isValidItem) {
alert(billItem);
var data = {
BillNo: $('#txtBillNo').val(),
CustomerName: $('#txtCustomerName').val(),
Address: $('#txtAddress').val(),
Gender: $('input[name="Gender"]:checked').val(),
BillDetail: billItem
}
//$(this).val() = "Please wait...";
$ajax({
url: "#Url.Action("Create", "Home")",
type: "POST",
data: {"json": JSON.stringify(data)},
dataType: "JSON",
success: function (d) {
if (d.status == true) {
alert("Successfully saved.");
billItem = [];
$('#txtBillNo').val('');
$('#txtCustomerName').val('');
$('#txtAddress').val('');
}
else {
alert("Error saving data.");
}
$('#submit').val('Save');
},
error: function () {
alert("Error saving data.");
}
});
}
And your Controller method will get the data like this:
using System.Web.Script.Serialization;
[HttpPost]
public ActionResult Create(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var BillNo = Convert.ToString(jsondata["BillNo"]);
var CustomerName = Convert.ToString(jsondata["CustomerName"]);
var Gender = Convert.ToString(jsondata["Gender"]);
//Your logic
return Json(new {status="true", msg= "Successful"});
}

Ajax call to async method returning file successfully but success/complete part of an Ajax request is not getting executed

I am trying to export selected records in to a file and reload the page to update the records in a current view. I am calling web api asynchronously to get all the records. An AJAX call is executing an action in a controller successfully and returning expected data without any error but none of the 'success', 'complete' or 'error' part of ajax function is executing. There are no errors in a developer tool of the browser, no exception, nothing unusual so its getting trickier for me to investigate this issue further. Can I request your a suggestions on this please? Thanks
View :
#Html.ActionLink("Export records", "Index", null, new { Id = "myExportLinkId")
Script :
$("a#myExportLinkId").click(function (e) {
var selected = "";
$('input#myCheckBoxList').each(function () {
if (this.checked == true) {
selected += $(this).val() + ',';
}
});
if (selected != "") {
$.ajax({
url: '/MyController/MyAction',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
'MyString': 'stringValue'
},
success: function (data) {
alert("success");
},
error: function () {
alert("error");
}
});
})
And the action/method looks like this :
[HttpGet]
public async Task<ActionResult> ExportNewOrders(string OrderIdString)
{
//code to create and store file
//actually want to send the file details as json/jsonResult but for testing only returning
//string here
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
}
Finally I have resolved this with Promisify functionality of an AJAX call. Obviously the json response I was returning had an issue so I have replaced
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
to
return new JsonResult(){
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
which has fixed the bug and the success function of ajax call got executed.
But other than this there were issues to wait until the file download (which involved encryption decryption, server validations etc) completes and then refresh the page. This I have resolved by implementing an ajax call with Promisify fuctionality. You can find codepen example here and the original post here.
Here is the complete code.
View/HTML
#Html.ActionLink("Export", "yourActionName", null, new { Id = "exportRequest", #onclick = "letMeKnowMyFileIsDownloaded();" })
Script/Ajax
function letMeKnowMyFileIsDownloaded() {
return new Promise(function (resolve, reject) {
$("a#exportRequest").on("click", function () {
$.ajax({
url: this.href + "?param=whatever params you want to pass",
dataType: "json",
data: {
'param1': 'value'
},
success: function (data) {
var a = document.createElement("a");
var url = '/yourControllerName/Download?fileGuid=' + data.guid + '&filename=' + data.fileName;//window.URL.createObjectURL(data);
a.href = url;
a.download = data.fileName;
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
resolve(true);
},
error: function (error) {
reject(error);
}
});
});
});
}
letMeKnowMyFileIsDownloaded()
.then(function (bool) {
if (bool) {
//alert("File downloaded 👇");
window.location.reload(1);
}
})
.catch(function (error) {
alert("error");
});
I have used nuget package ClosedXML to handle excel file functionality. Using the stream to create and download the data in excel file without storing the file physically on the server.
And in the controller
//can be async or sync action
public async Task<ActionResult> Index(YourModel model)
{
//do stuff you want
var exportOrders = your_object;
//using DataTable as datasource
var dataSource = new DataTable();
//write your own function to convert your_object to your_dataSource_type
dataSource = FormatTypeToDataTable(exportOrders);
if (dataSource != null && dataSource.Rows.Count > 0)
{
//install ClosedXML.Excel from nuget
using (XLWorkbook wb = new XLWorkbook())
{
try
{
var handle = Guid.NewGuid().ToString();
wb.Worksheets.Add(dataSource, "anyNameForSheet");
string exportFileName = "yourFileName" + ".xlsx";
MemoryStream stream = GetStream(wb);
TempData[handle] = stream; exportFileName);
return new JsonResult()
{
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
catch (Exception ex)
{
//ModelState.AddModelError("", ex.Message);
}
}
}
}
public virtual ActionResult Download(string fileGuid, string fileName)
{
if (TempData[fileGuid] != null)
{
var stream = TempData[fileGuid] as MemoryStream;
var data = stream.ToArray();
return File(data, "application/vnd.ms-excel", fileName);
}
else
{
return new EmptyResult();
}
}

Asp.net core MVC and JQuery submit

I have this code(JQuery) in my View:
$("form").submit(function (e) {
e.preventDefault();
var form = this;
var link = '#Url.Action("Action", "Controller")';
var args = {
MyFVal: MyFVal.val(),
MySVal: MySVal.val()
};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
alert(data.acces);
if (data.acces) {
AllEnable();
form.submit();
}
else {
alert(data.erromessage);
}
},
error: function () {
alert("Error. Kontaktujte správce.");
}
});
});
When I gets submitted then I have this if in my save action.
if (Request.Form.ContainsKey("Insert"))
{
// do code that is supposed to run
}
else if (Request.Form.ContainsKey("Edit"))
{
// do another code
}
My problem is that because I submitted form by JQuery this if and elseif never gets executed.
Thanks for any help!
You might want to pass value for your requirements in Action condition. See operationType sample parameter
var obj = {
UniqueId: modelUniqueId.val(),
Name: modelName.val(),
operationType: $("[name=operationType]").val()
};
$.ajax({
type: "POST",
url: '/hrms/Class/Index',
data: obj,
success: function (result) {
if (result.success == true) {
createAndProcessPageAlert("success", result.message);
}
else {
createAndProcessPageAlert("error", result.message);
}
And in your Controller \ Action
[HttpPost]
public JsonResult Index(string operationType, ClassModel model)
{
var result = new HttpResponseModel<ClassModel>();
var user = Request.GetUserProfile();
if (operationType == "add")

Parameter in my C# controller read as null from the AJAX call

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

Transforming List into a Json C#

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.

Categories

Resources