Cannot show value after AJAX call (ASP.NET MVC) - javascript

I have two <p> fields where I need to assign text
Here is html code:
<p id="appId" style="visibility: hidden;"></p>
<p id="calculationId" style="visibility: hidden;"></p>
I make AJAX call like this
$('#openCalculationConsumables').click(function() {
addConsumables();
});
function addConsumables() {
var patientName = $('#patientsId').val();
var finding = $('#findingvalue').val();
var procedure = $('#procedurevalue').val();
var model = {
findingValue: finding,
procedureValue: procedure,
patientId:patientName
}
$.ajax({
url: '#Url.Action("AddIndividualCalculation", "Calculations")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
$('#masters_data').load('#Url.Action("IndividualCalculationConsumables", "Calculations")', function() {
var list = data;
$('#calculationId').text(list[0].calcid);
$('#appId').text(list[0].appid);
});
}
});
}
And here is my back end code:
public JsonResult AddIndividualCalculation(string findingValue, string procedureValue,int patientId)
{
using (var ctx = new ApplicationDbContext())
{
Calculation calc = new Calculation
{
};
ctx.Calculations.Add(calc);
ctx.SaveChanges();
int calculationId = calc.Id;
Appointment app = new Appointment
{
Calculation_id = calculationId,
FindingContent = findingValue,
ProcedureContent = procedureValue,
Patient_id = patientId
};
ctx.Appointments.Add(app);
ctx.SaveChanges();
int appointmentId = app.Id;
var items = new
{
appid = appointmentId,
calcid = calculationId
};
return Json(items,JsonRequestBehavior.AllowGet);
}
}
I set breakpoint and see , that I have values in items. In console log I have this {appid: 1006, calcid: 1006}
But I cant assign it to <p> and have this error.
Cannot read property 'calcid' of undefined
Where is my problem?
Thank's for help.

$('#masters_data').load('#Url.Action("IndividualCalculationConsumables", "Calculations")', function() {
var list = data;
$('#calculationId').text(list[0].calcid);
$('#appId').text(list[0].appid);
});
list[0] is not defined as you are returning just an anonymous object not a list of objects
new {
appid = appointmentId,
calcid = calculationId
};

Related

Cannot POST more than one value with AJAX

I stucked on one thing. I have a 2 grid inside checkboxes. When I selected that checkboxes I want to POST that row data values like array or List. Actually when i send one list item it's posting without error but when i get more than one item it couldn't post values.
Example of my grid
Here my ajax request and how to select row values function
var grid = $("#InvoceGrid").data('kendoGrid');
var sel = $("input:checked", grid.tbody).closest("tr");
var items = [];
$.each(sel, function (idx, row) {
var item = grid.dataItem(row);
items.push(item);
});
var grid1 = $("#DeliveryGrid").data('kendoGrid');
var sel1 = $("input:checked", grid1.tbody).closest("tr");
var items1 = [];
$.each(sel1, function (idx, row) {
var item1 = grid1.dataItem(row);
items1.push(item1);
});
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
data: JSON.stringify({ 'items': items, 'items1': items1, 'refnum': refnum }),
contentType: 'application/json',
traditional: true,
success: function (msg) {
if (msg == "0") {
$("#lblMessageInvoice").text("Invoices have been created.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
var del1 = $("#InvoiceDetail").data("kendoWindow");
del1.center().close();
$("#grdDlvInv").data('kendoGrid').dataSource.read();
}
else {
$("#lblMessageInvoice").text("Problem occured. Please try again later.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
return false;
}
}
});
This is my C# part
[HttpPost]
public string CreateInvoice(List<Pm_I_GecisTo_Result> items, List<Pm_I_GecisFrom_Result> items1, string refnum)
{
try
{
if (items != null && items1 != null)
{
//do Something
}
else
{
Log.append("Items not selected", 50);
return "-1";
}
}
catch (Exception ex)
{
Log.append("Exception in Create Invoice action of HeadOfficeController " + ex.ToString(), 50);
return "-1";
}
}
But when i send just one row it works but when i try to send more than one value it post null and create problem
How can i solve this? Do you have any idea?
EDIT
I forgot to say but this way is working on localy but when i update server is not working proper.
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
async: false,
data: { items: items, items1: items1 }
success: function (msg) {
//add codes
},
error: function () {
location.reload();
}
});
try to call controller by this method :)

ASP.NET MVC ADO.NET Query per table row

Here I have this table:
If I click the button, I want to pass the table per row to the controller, then perform ADO.NET Query per row, like for example, perform "UPDATE tbluser SET note='INACTIVE' WHERE id=#id" per row.
One of the main purpose of this is when i filter the table, only the visible rows will be passed.
I already have a code here to pass to controller using AJAX but I don't know what to do afterwards.
JS:
var HTMLtbl =
{
getData: function (table) {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
//I don't know what to do here now, please help
}
My Solution based on Mostafa's answer:
JS:
var HTMLtbl =
{
getData: function () {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("#btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
string result = string.Empty;
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
con.Open();
foreach (var arr in array)
{
SqlCommand cmd = new SqlCommand("UPDATE tbluser SET remark='INACTIVE' WHERE id = #id", con);
cmd.Parameters.AddWithValue("#id", arr[0]);
cmd.ExecuteNonQuery();
}
con.Close();
}
catch (Exception ex)
{
result = ex.Message;
}
return Json("Records updated successfully.", JsonRequestBehavior.AllowGet);
}
I can now use this for more complicated stuff, thanks
If you want to update a custom row you can add a button for each row with custom text and icon, then add a "data-" attribute to this button and path your row id,
<input type="button" data-rowId="1" class="changeActivationState">activate</input>
in this example I added a data field to my imput after that I define this javascript method:
$(".changeActivationState").click(function(){
$(this).data("rowId")//get the selected row id and call you service
});
using this code you can read first element for each row and perform a web service call for all rows
var arr = [];
$("#yourtable tr").each(function(){
arr.push($(this).find("td:first").text()); //put elements into array
});
and using this code you can read all rows into a json object
var tbl = $('#yourtable tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
assume that you passed the list to action
int[] passedIDsfromBrowser = ///filled with data that comes from browser;
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
command.CommandText = "Update MYTABLENAME Set Active = true where ID in (" string.Join(",", passedIDsfromBrowser ) + ")";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
this is a pseudo code.
or if you want a loop and updating each row with a loop
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
connection.Open();
for(int i = 0 ; i < passedIDsfromBrowser.Length; i++){
command.CommandText = "YOURQUERY";
command.ExecuteNonQuery();
}
connection.Close();

A script for upadate textbox's value in asp.net mvc didn' work

I want to update textbox's value(that contains cookie's value) using Ajax in asp.net MVC5 . I'm very new in JavaScript and I wrote these codes , but my code didn't work . I didn't get any error but it's not working. I wrote JavaScript in foreign file 'UpdateTxtBox.js' and I added <script src="~/Scripts/UpdateTxtBox.js"></script> to Layout .
Could anyone tell me what's the problem ?
$(function () {
$("textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
a part of Basket.cshtml
#using (Html.BeginForm("AddToCart", "Goods", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(modelItem => item.Count, new { #class="text textCountProduct" , style="width:40px;" , productid=item.GoodDetails.DetailsGoodID})
}
Good controller
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
//Script = "alert('Good added successfully');",
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
Update post :
I added [HttpPost] to controller action result and add some alert to javascript
$(function () {
alert("aleeeert");
$(".textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
alert(count);
alert(id);
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
it's working fine but when I refresh page , data didn't saved
Since you have specified textCountProduct as CSS class, you need to prefix it with . to use Class Selector (“.class”), As of now its looking for Element textCountProduct which obviously doesn't exists.
Use
$(".textCountProduct").change(
You have made mistake here $("textCountProduct") use . as selector.
It should be $(".textCountProduct")
and
Check path of your script included
<script src="~/Scripts/UpdateTxtBox.js"></script>

The ajax call in the Jq function of a bootstrap toggle does not get called

I am trying to call a function that when clicked goes to the controller (I am working on MVC project) but for some unknown reason the function does not get called. I have used this before with other buttons and grid selections and it used to work properly, can any one help with this question?
I have a bootstrap toggle button that is as follows:
<input id="toggle-event" type="checkbox" data-toggle="toggle" data-on="Enabled" data-off="Disabled ">
The function is as follows:
$(function() {
$('#toggle-event').change(function() {
$('#console-event').html('Toggle: ' + $(this).prop('checked'))
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig = nodeURL + ".CONFIG";
var nodeAdd = nodeURL + ".CONFIG.Enable";
var ListNodedetS = [];
var ListNodedetI = [];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetailsString: ListNodedetS,
ListNodeDetailsInt: ListNodedetI,
ListMethod: Listmet
};
var temp = {
url: "/Configuration/CallMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};
})
})
Controller part:
public bool CallMethod(List<string> ListNodeDetailsString, List<string> ListNodeDetailsInt, List<string> ListMethod)
{
var AddMethod = RxMUaClient.CallMethod(ListNodeDetailsString,ListNodeDetailsInt, ListMethod, "127.0.0.1:48030");
return AddMethod;
}
The ajax call was used before on different buttons and it worked normally, but now since it is called as an action of checking the bootstrap toggle it does not work.
The other jq that works:
$('#AddActivity').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeName = $("#ActivityName").val();
var nodeType = $("#ActivityType").data("kendoComboBox").value();
var nodeConfig = nodeURL + ".CONFIG";
var nodeAdd = nodeURL + ".CONFIG.AddActivity";
var ListNodedetS = [nodeName];
var ListNodedetI = [nodeType];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetailsString: ListNodedetS,
ListNodeDetailsInt: ListNodedetI,
ListMethod: Listmet
};
var temp = {
url: "/Configuration/CallMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};

How to get rid of Serialization in MVC

I have created a jQuery code which will take a form(which is in my view) and it will serialize it and it will post that to my controller.......Jquery code looks like this......
$(document).ready(function () {
$('#submit').click(function () {
var jsonObj = $('#form').serialize();
$.ajax({
type: "POST",
url: "../Home/Index",
data: JSON.stringify({ "cus": jsonObj }),
success: function(data){
alert(data + "done");
},
error:function(){
alert("Error!!!!");
}
});
});
});
This is how my controller method looks like:..........
[HttpPost]
public ActionResult Index(Customer cus)
{
string str = null;
if (cus.Name == "jude")
str = "Success";
else
str = "Error!!";
return Json(str);
}
Now i need to undo the serialization inside my controller method......can someone please give me an idea to do this..........
I have tried two ways to do this but didn't work.....
1 - var model = (Customer)cus.Deserialize();
2 - JavaScriptSerializer js = new JavaScriptSerializer();
var cus1 = js.Deserialize<Customer>(cus);

Categories

Resources