Call ViewBag in Jquery to get the value from controller - javascript

I am calling ViewBag.DeliveryDatebySupplier to update my textbox or just to alert. The value was always null. But when I debug and check the ViewBag in controller it has the date value.
Controller
if (ds.Tables[0].Rows.Count == 1)
{
string dt = ds.Tables[0].Rows[0]["DeliveryDt"].ToString();
DateTime myDate = Convert.ToDateTime(dt);
dt = myDate.ToString("yyyy-MM-dd");
ViewBag.DeliveryDatebySupplier = dt.ToString();
//Session["NewDeliveryDate"] = dt.ToString();
}
Jquery
function getDeliveryDateBySupplier() {
var _storeID = $('#ddlStoreID :selected').val();
var _SupplierID = $('#ddlSupplier :selected').val();
var url = "#Url.Content("~/Home/DeliveryDatebySupplier")";
$.ajax({
data: {
StoreID: _storeID,
SupplierID: _SupplierID
},
type: 'POST',
cache: false,
dataType: 'json',
url: url,
success: function (result) {
var newDeliveryDate = '#ViewBag.DeliveryDatebySupplier';
alert(newDeliveryDate);
},
error: function (ex) {
alert("Error getDeliveryDateBySupplier()");
}
});
}

Assuming the action called DeliveryDatebySupplier in the HomeController is the method to set ViewBag.DeliveryDatebySupplier, then this will not work unfortunately.
The script will be generated when the full page was generated and at that time, the value would not have been set yet.
I would advise, rather than using the viewbag, return the value when DeliveryDatebySupplier is called in your script.
Controller will be something like this then
if (ds.Tables[0].Rows.Count == 1)
{
string dt = ds.Tables[0].Rows[0]["DeliveryDt"].ToString();
DateTime myDate = Convert.ToDateTime(dt);
dt = myDate.ToString("yyyy-MM-dd");
return new JsonResult
{
data = new
{
DeliveryDatebySupplier = dt.ToString()
}
};
}
and jquery would change to something like this
success: function (data) {
if (data) {
var newDeliveryDate = data.DeliveryDatebySupplier
alert(newDeliveryDate);
}
else {
//Error
}
},

Related

MVC Controller is not receiving the values that comes from the Ajax /Javascript script

I debugged the JS and Ajax code with console.log. I can see that what I entered into the textbox, is displayed in the console. However, when these values are supposed to send to the controller, they are empty or null when I hover over the tbl_stuff List. Not sure where I am making a mistake.
Here is the JS:
$("body").on("click", "#btnSave", function () {
var table = $("table tbody");
var array= new Array();
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
Amount = $(this).find('.val').val();
valuestoupdate = { Amount: amount };
array.push(valuestoupdate);
});
$.ajax({
type: "POST",
url: "#Url.Action("StuffAction","Home")",
data: JSON.stringify(array),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) saved.");
}
});
Here is the controller action:
public JsonResult StuffAction(List<tbl_Stuff> stuffs)
{
int getID = (int)TempData["id"];
TempData.Keep();
var GetData = _context.tbl_Detail.Where(x => x.detId == getID).FirstOrDefault();
if (GetData != null)
{
foreach (tbl_Stuff moreThings in stuffs)
{
tbl_Stuff stuff = new tbl_Stuff();
stuff.Amount = moreThings.Amount;
_context.tbl_Stuff.Add(stuff);
}
}
int insertedRecords = _context.SaveChanges();
return Json(insertedRecords);
}
I get an error saying that moreThings.Amount is empty. But during debugging, the JS code gets the value entered into the textbox.
The .Net routing can't match the request
change the action signature to public JsonResult StuffAction(List< string > stuffs)
or in your ajax call change the array to an array of objects matching the properties of tbl_Stuff

error in serialization javascript from json to text

i have an error in serialisation i need someone to fix it and that 's code controller
public string Getrowselec(string id)
{
GestionprojetEntities ddb = new GestionprojetEntities();
Ressourcehumaine _ressource = new Ressourcehumaine();
_ressource = ddb.Ressourcehumaine.Find(Convert.ToInt32(id));
int id_ressource = int.Parse(id);
var query = (from u in ddb.Ressourcehumaine
where (u.Id == id_ressource)
select new
{
id = u.Id,
nom = u.Nom,
prixrevient = u.Prixrevient,
prixvente = u.Prixvente,
coutdirect = u.Coutdirect,
});
string javascriptJson = JsonConvert.SerializeObject(query);
return javascriptJson;
and this is my code in twig code javascript:
function Getrows(s, e) {
debugger;
var id = e.visibleIndex;
var key = s.GetRowKey(e.visibleIndex);
idProduit = key;
$.ajax({
url: "/Projet/Getrowsselec?id=" + key,
type: "POST",
dataType: "text",
success: function (response) {
debugger;
$("#nomclient_I").val(jsonObject[0]['nom']);
$("#codeclient_I").val(jsonObject[0]['id']);
}
})
}
can someone help me fix this issue the error in serialisation i think some error in serialisation
from json to text
i think that you need to add this to your response ajax try it and tell me if it work or not
success: function (response) {
debugger;
var jsonObject = JSON.parse(response);
$("#nomclient_I").val(jsonObject[0]['nom']);
$("#codeclient_I").val(jsonObject[0]['id']);
}

Javascript list passing to c#

I have a Asp.net MVC program in which i want to get a list from the View using Javascript and pass that list to the controller. I want to the variables in the list to be string type except for one to be int32.
The problem is the list is either empty or does not pass.
I tried to use stringify but it doesn't fill the requirments.
Here is the code from the javascript part:
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val();
var nodeType = $("#ColumnType").data("kendoComboBox").value();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var ListNodeDetails = JSON.stringify(ListNodedet);
var ListMethod = JSON.stringify(Listmet);
var select = 1;
var url = "/Configuration/CallMethod";
$.get(url, { ListNodeDetails:ListNodeDetails, ListMethod:ListMethod }, function (data) {
$("#Data2").html(data);
});
})
The C# code for the controller were it calls another method in models:
public bool CallMethod(List<Variant> ListNodeDetails, List <string> ListMethod)
{
var AddMethod = RxMUaClient.CallMethod(ListNodeDetails, ListMethod, "127.0.0.1:48030");
return AddMethod;
}
The Model:
public static bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod, string iPAddress)
{
var serverInstance = GetServerInstance(iPAddress);
if (serverInstance == null)
return false;
return serverInstance.CallMethod(ListNodeDetails, ListMethod);
}
The service model
public bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod)
{
try
{
if (_mSession == null)
{
return false;
}
NodeId objectID = NodeId.Parse(ListMethod[0]);
NodeId Methodtype = NodeId.Parse(ListMethod[1]); ;
List<Variant> inputArguments = ListNodeDetails;
List<StatusCode> inputArgumentErrors = null;
List<Variant> outputArguments = null;
StatusCode error = _mSession.Call(
objectID,
Methodtype,
inputArguments,
new RequestSettings() { OperationTimeout = 10000 },
out inputArgumentErrors,
out outputArguments);
if (StatusCode.IsBad(error))
{
Console.Write("Server returned an error while calling method: " + error.ToString());
return false;
}
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
return false;
}
}
At the end it calls some functions using OPC UA to add data.
I have changed it to be ajax function and it works well but only with one list form the lists passed to the method!
I dont know if this is because i read values from kendo box and text box, and they are different types but i tried to stringfy it and it still does not work. On the console both lists are out as strings. So still got a problem with passing the first List "ListNodeDetails"!
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val().toString();
var nodeType = $("#ColumnType").data("kendoComboBox").value().toString();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetails: ListNodedet,
ListMethod: Listmet
};
var url = "/Configuration/CallMethod";
console.log(params); // added sanity check to make sure data is correctly passed
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);
}
};
$.ajax(temp);
})

Why doesnt this javascript code work?

I have a javascript function
function TxEncrypt(event)
{ //perform encryption of token data, then submit the form like normal
//obtain public key and initial JSEncrypt object
var txPubKey = txJ$(".zwitch_encryptionkey").val();
var txEncrypter = new JSEncrypt();
txEncrypter.setPublicKey(txPubKey);
//get Data and encrypt it
var txData = '{}';
var txCryptData = '';
if(txJ$(".zwitch_data").length > 1)
{ //if there are more than one element with this class, convert it to json string
txData = txJ$(".zwitch_data").serializeObject();
txCryptData = txEncrypter.encrypt(JSON.stringify(txData));
}
else
{ //else, just encrypt the value
txData = txJ$(".zwitch_data").val();
txCryptData = txEncrypter.encrypt(txData);
}
dataString = txCryptData; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
alert(dataString);
}
I could get the value of dataString.But the ajax parrt is not working.I have added the jquery library.But doesnt seem to work
What's the error you are getting?
I think this should be:
$.ajax({
type: "POST",
url: "tokenize.php", //removed the dot
.....

How do I get the changed element in a multiselect, using KendoUI?

I have a multiselect-list that acts as holder for a list of tags. I can't seem to figure out how to properly get the value of the item being changed and passed along with the changed-event. Here's my Kendo multiselect:
#(Html.Kendo().MultiSelect()
.Name("tags")
.Placeholder("No tags selected for this unit")
.BindTo(new SelectList(Model.TagsAvailable))
.Events(e => e
.Select("select")
.Change("change"))
.Value(Model.TagsSelected.ToArray())
)
And here are my js-methods:
function select(e) {
var dataItem = this.dataSource.view()[e.item.index()];
var param = dataItem.Text;
var url = '/UnitDetails/TagUnit/#Model.UnitId';
$.ajax({
url: url,
data: { selectedItem: param },
type: 'GET',
dataType: 'json',
success: function (data) {
// ...
},
error: function () {
// ...
}
});
};
function change(e) {
var dataItem = this;
var param = dataItem.element.context.innerText;
var url = '/UnitDetails/UnTagUnit/#Model.UnitId';
$.ajax({
url: url,
data: { selectedItem: param },
type: 'GET',
dataType: 'json',
success: function (data) {
// ...
},
error: function () {
// ...
}
});
};
My problem beeing that I feel the assignment of param is just quick and dirty. Surely, there must be some other, more correct way of going about this?
There is no easy way (afaik) for knowing the changes. So, let do it by ourselves.
First, I'm going to save the old value using the following function.
function saveCurrent(multi) {
multi._savedOld = multi.value().slice(0);
}
Where multi is the multi-select that we pass to the function as argument (so you can use the function for multiple multiselects).
Then, you need to implement change as follow:
change : function (e) {
// Retrieve previous value of `multiselect` saved using previous function
var previous = this._savedOld;
// These are current values.
var current = this.value();
// Let's save it for the next time
saveCurrent(this);
// The difference between previous and current are removed elements
var diff = $(previous).not(current).get();
console.log("removed", diff);
// The difference between current and previous, are added elements
diff = $(current).not(previous).get();
console.log("added", diff);
}
Running example here http://jsfiddle.net/OnaBai/MapVN/
Nice answer OnaBai! very useful and helpful.
I had the same Nickla's problem.
But, I needed to "save current values" at dataBound event. And it works (logging the changed values).
If you start deleting an item, it fails because the function recognizes the "change" as an "item add".
This is what I did
function dataBound(ev) {
saveCurrent(this);
}
function saveCurrent(multi) {
multi._savedOld = multi.value().slice(0);
}
function change(ev) {
var previous = this._savedOld;
var current = this.value();
saveCurrent(this);
var diff = $(previous).not(current).get();
console.log("removed", diff);
var removedSkill = diff;
console.log("removedSkills", removedSkill);
diff = $(current).not(previous).get();
var addedSkill = diff;
console.log("added", diff);
console.log("addedSkills", addedSkill);
if (addedSkill.length > 1 || removedSkill.length > 1) {
if (addedSkill.length > 1) {
addedSkill = addedSkill[addedSkill.length - 1];
alert("Added skill code: " + addedSkill.toString());
}
if (removedSkill.length > 1) {
removedSkill = removedSkill[removedSkill.length - 1];
alert("Removed skill code: " + removedSkill.toString());
}
}
else {
if (addedSkill.length > 0) {
alert("Added skill code: " + addedSkill.toString());
}
if (removedSkill.length > 0) {
alert("Removed skill code: " + removedSkill.toString());
}
}
$.ajax({
url: "SomeUrl",
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({ removedSkill: removedSkill, addedSkill: addedSkill })
});
}
Thanks again!
Iván

Categories