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']);
}
Related
I am wanting to pass a dictionary of type <int,int> to my controller via an Ajax post.
The main reason here is the post may have between 1-3 key value pairs here (none of these values are known at compile time) and in the future it may go up to 5.
Also in the post I have to pass in some other data, such as Id and name, which all works as normal.
How would I construct this dictionay in the javascript then send it via the JQuery post and finally receive it on the controller to process?
Edit 2:
I have decided to just solve this with a post for each value instead of trying to pass a dictionary.
EDIT:
Here is my source for the function so you can see what I am trying:
function BindAddMenuItem() {
$(".AddMenuItem").click(function (e) {
e.preventDefault();
//get header id from link by removing addmenuitem from this.id
var currentId = $(this).attr("id").replace("AddMenuItem", "");
//get itemnumber, itemname, itemdetails from textboxes with same header id
var restaurantId = jQuery.trim($("#RestaurantId").val());
var itemNumber = jQuery.trim($("#ItemNumber" + currentId).val());
var itemName = jQuery.trim($("#ItemName" + currentId).val());
var itemDetails = jQuery.trim($("#ItemDetails" + currentId).val());
var costs = new Object();
//select all textboxes with class "Header" + currentId
$(".Header" + currentId).each(function (i) {
var optionId = $(this).attr("id").replace("Option", "");
costs[optionId] = $(this).val();
});
$.ajax(
{
type: "POST",
url: "/Menu/AddMenuItem",
data: "reastaurantId=" + restaurantId + "&menuHeaderId=" + currentId + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails + "&costs=" + costs,
dataType: "html",
success: function (result) {
var domElement = $(result);
$("#MenuContainer").replaceWith(domElement);
var newNum = parseInt(itemNumber) + 1;
$("#ItemNumber" + currentId).val(newNum);
BindAllBehaviours();
}
});
});
}
Something like (javascript)
dict = new Object();
dict['12'] = 5;
dict['13'] = 6;
dict['1000'] = 21;
dict['9'] = 13;
dict['13'] = 48;
$.post('/client.mvc/mypostaction/', { myDictionary: dict });
You can then post the dict object to your controller using a Dictionary<int, int> as property type.
ActionResult MyPostAction(Dictionary<string, int> myDictionary)
edit from author's code second time:
The following works for me, when having a Dictionary<string, int> kvPairs. <int, int> isn't going to work after all.
Make your post like:
var dict = new Object();
dict['13'] = 9;
dict['14'] = 10;
dict['2'] = 5;
$.post('controller.mvc/Test', { 'kvPairs': dict }, function(obj) { $('#output').html(obj.Count); });
JavaScript object / dictionary has to be passed as a list of key-value pairs to ASP.NET MVC controller when Dictionary<TKey, TValue> is expected. Example:
If you have a dictionary like this:
public Dictionary<string, decimal?> SomeMapping { get; set; }
then you have to use something like this in your JavaScript:
var sourceMapping = { a: 1, b: 1.5, c: null };
var SomeMapping = [];
for (var key in sourceMapping) {
if (sourceMapping.hasOwnProperty(key)) {
SomeMapping.push({ Key: key, Value: sourceMapping[key] });
}
}
I've used this approach in asynchronous POST request (sent using jQuery) that had content type set to 'application/json' (this may or may not be important in your case).
Client (JavaScript):
var dict = new Object();
dict.Key1 = "Value1"
dict.Key2 = "Value2"
$.post('/YourController/YourAction/', dict);
NOTE: The "dict" objects gets serialized behind the scenes before being sent to your action.
Server:
public ActionResult YourAction()
{
string postData = string.Empty;
using (StreamReader sr = new StreamReader(Request.InputStream))
{
postData = sr.ReadToEnd();
}
//Load post data into JObject (Newtonsoft.Json)
JObject o = JObject.Parse(postData);
//Extract each key/val
string val1 = (string)o["Key1"];
//Do whatever....
}
None of these worked for me except for mczers, but he doesn't show all the steps, and makes it difficult when you're trying to remember how you set up an ajax request. So I wanted to put everything that actually just works. First, in JavaScript:
var validDict = new Array();
validDict[0] = { key: 1, value: 4 }
validDict[1] = { key: 42, value: 5}
var path = "#Url.Action("ControllerName", "ActionName")";
$.ajax({
url: path,
type: "POST",
data: JSON.stringify(validDict),
contentType: "application/json; charset=utf-8",
async:false,
success: function(status, xhr)
{
alert(status);
},
error: function(xhr, status, error)
{
alert(error);
}});
Then in your controller:
[HttpPost]
public ActionResult ActionName(Dictionary<int, int> validDict)
{
// doStuff();
return Content("Success");
}
A dictionary of the kind IDictionary<string, string> on server side can be posted from javascript like
{"Key1": "Value1", "Key2": "Value2"}
on the Server Side in ASP.NET Web API
[HttpPost]
public IHttpActionResult([FromBody]IDictionary<string, string> requestParam){
}
Above example is for an Http POST with the Json data in the Body
For passing a Dictionary I found the following working answer:
submitting-a-dictionary-to-an-asp-net-mvc-action
#model WebApplication3.Controllers.ExampleViewModel #{ ViewBag.Title = "New";
var first = Guid.NewGuid(); var second = Guid.NewGuid(); }
<h2>New</h2>
#using (Html.BeginForm(new { action = "create", controller = "home" })) {
foreach (var kvp in Model.Values) {
<p>
<input type="text" name="Model.Values[#first].Key" value="#kvp.Key" />
<input type="text" name="Model.Values[#first].Value" value="#kvp.Value" />
<input type="hidden" name="Model.Values.Index" value="#first" />
</p>
}
you have to generate A Guid for the dictionary index, and you have to create 3 inputs, one for the Key, one for the Value and one for the Index of the Dictionary
Also I have submited using Jquery with the following:
$('form#frmFormId').submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
//debugger;
$('#cover-spin').show(100);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false
}
);
return false;
});
I found some similar questions but none of them resolve my problem.
The problem I have is that my data from my AJAX-call is empty but my controller return exactly I want him to return.
I tried to add a contentType, but neither contentType nor ContentType worked for me.
What am I doing wrong?
JavaScript:
function AddFunction() {
var ergebnis = "";
var zahl1 = $("#txt_1").val();
var zahl2 = $("#txt_2").val();
$.ajax({
async: false,
cache: false,
type: 'POST',
url: '/Calc/Add',
dataType: 'JSON',
data: {
'val_1': zahl1,
'val_2': zahl2
},
success: function (data) {
ergebnis = data.result;
alert(ergebnis);
},
error: function () {
alert("Fehler");
}
});
}
Controller:
public ActionResult Add(string val_1, string val_2)
{
string sUri = "http://192.168.111.173:35145/temppath/GVCalc/1.0/add";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(sUri);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"field_1\":\"" + val_1 + "\"," +
"\"field_2\":\"" + val_2 + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result = DeserializeFromStream(httpResponse.GetResponseStream());
return Json(result);
}
Controller result:
{{
"result": 3
}}
Ajax data:
kinda empty / no result at all
Edit:
DeserializeFromStream Method:
public static object DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);
}
}
I solved my problem by sending a string and parse it in JavaScript. This worked fine for me :)
C#:
return Json(result.ToString());
JavaScript:
var ergebnis_json = JSON.parse(data)
ergebnis = ergebnis_json.result;
$("#ergebnis").val(ergebnis);
Thanks everyone for their help :)
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);
})
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
.....
I can't seem to get around this issue... Json I'm trying to pass to an MVC Controller keeps coming out like this
"\"{MaterialQuantity: { MaterialID :18, Quantity:1}}\""
This is the code that generates it:
function CreateJsonForQuantities() {
var inputs = $('input[name=MaterialQuantity]');
var total = inputs.length;
var data = "";
inputs.each(function (index) {
data = data + $(this).val();
if (index != total -1)
data = data + ',';
});
return data;
}
And this is the hidden which it reads data from (of course this is auto-generated as well)
<input name="MaterialQuantity" type="hidden" value="{MaterialQuantity: { MaterialID :12, Quantity:5}}" />
What am I doing wrong?
UPDATE
Ok so now I'm properly getting json object and my ajax requests looks like this. Problem now is that it does pass proper objects but all values are null in the controller action :(
var form_data = CreateJsonForNorm();
var quantity_data = CreateJsonForQuantities();
var data = { norm: form_data, mqvm: quantity_data };
$.ajax({
type: "POST",
url: form.attr("action"),
data: data,
success: function () {
location.href = "#Url.Action("Index")";
('#addDialog').dialog("close");
},
error: function () {
alert("Error");
}
});
Try using JSON.stringify(data) in your request