My problem is currently : How to pass a JSON Object (As it is or as a C# object deserialized with Newtonsoft.Json) to a javascript file.
I tried the following method :
Response.Write(string.Concat("<input id='data' type='hidden' value='", json_file, "' />"));
but when the json file is rendered in HTML (as a html attribute) it stops on the quote character, i tried to escape it but it's not working either.
So when in my javascript file i use JSON.parse() the syntax is not valid.
Problem Solved :
- Declared a javascript variable Data in my .cshtml file, put the jsonfile as a #ViewBag element inside.
- got it in my javascript by window.Data
- parsing it as json, using it, magic done.
(Thanks for those who answered)
If this is a json object, why not insert the object in a javascript variable on the page, as presumably you want to use the variable e.g. in Ajax?
function someThingClicked(){
var myObject = <%= json_file %>;
$.ajax({
type: "POST",
url: "SomeUrl",
data: myObject,
success: function () { },
contentType: "application/json; charset=utf-8",
dataType: "json"});
}
This should serve something like the below to the browser:
var myObject = {
someField : 'someValue'
};
...
If you are using razor, you would write it out something like:
var myObject = #Html.Raw(ViewBag.json_file);
Assuming that you've added the json_file string into ViewBag from your controller.
in this case you can try use JsonResult
Try this please
Response.Write(string.Concat("<input id='data' type='hidden' value=\"", json_file.Replace('\"', '\''), "\" />"))
it's a result of you concatenation results in termination of the valuesttribute value before you intended. E.g. you have a 'character in the json_file
as an example if the file contains
var x = 'this is a string'
then the result of your concatenation would yield invalid html
<input id='data' type='hidden' value='var x = 'this is a string'' />
notice that the value attribute is terminated after var x = and that the final "attribute" string is missing an = prior to the value (the empty string '')
to avoid that you should assign the json to a variable and then assign that value as the value to the input element
Response.Write(string.Concat("<input id='data' type='hidden'/>",
"<script>$(function(){var x = ", json_file,
";$("#data").val(JSON.stringify(x));</script>");
(assuming you are already using jQuery otherwise you'd have to do it with plain vanilla JS which is a little more work but can be done
An other solution instead of printing json string inside the html attribute
Create an action that returns your json in your controller
public string GetData()
{
//read your json file
return json_file; //return your json string
}
On View side, put your input tag and fetch json_file through an ajax request
<input id='data' type='hidden' />
<script>
$(function () {
$.post("/yourControllerName/getData", {}, function (response) {
$("#data").val(response);
},'json');
});
</script>
Related
I wish to simply do an AJAX call to a method expecting a List of Key and value pairs, but I have no idea how to do this. I tried the following:
Server method:
UpdateBranches(List<KeyValuePair<string, string>> brancheItems)
data to be send:
var brancheItems = [];
businessActivities.forEach(f =>
brancheItems.push({
Key: f.sbiCode,
Value: f.sbiCodeDescription
})
This seemed to give me an array of objects with key and value properties. (network tab showed it), but it did not work. I also tried to make an array of objects with one property (propertyname is the key, value is the value):
for (var itemIndex in items[index].businessActivities) {
var key = items[index].businessActivities[itemIndex].sbiCode;
brancheItems.push({
key: items[index].businessActivities[itemIndex].sbiCodeDescription
});
}
Note that on the server I seem to receive an array/list of 3 items with two properties, but the properties are always empty. Does anyone know the correct format for the data to be send
I think you can simply create your object like this:
var ParamtersContainer = new Object();
ParamtersContainer = {
"PatientName": 'Alameer',
"ServiceDate": '12/12/2017',
"ProviderName": 'ahmed'
};
Then make it as data parameter in your ajax request, receive it as a dictionary in your c# action.
Use something like this.
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
data:JSON.stringify( {brancheItems: brancheItems}),
success: function (data) {
alert("Succeded");
}
});
And use the bracket notation:
Instead of brancheItems.push({ key : value });
use
var object = {};
object[key] = value;
brancheItems.push(object);
I have following input field.
<input class="book_now_modal BClick" type="text" id="destinationFrom_modal" name="destinationFrom_modal" placeholder="#ViewBag.AmritsarList[0].Destination">
time to time I want to change the value inside the view bag.is there a way to give dynamic value to the viewbag item.I have tried with jquery as below.
$(".AClick").click(function () {
//$(".BClick").attr("placeholder"," ");
var s = parseInt($(this).attr('id'));
var neededVAl = "##ViewBag.AmritsarList"+"["+s+"]"+".Destination";
alert(neededVAl);
var b = $(".BClick");
$(this).attr("placeholder",neededVAl);
});
like this I replace the placeholder as an alert it gives #ViewBag.AmritsarList[1].Destination but it didn't change the placeholder.how can I do that.
var neededVAl = "##ViewBag.AmritsarList"+"["+s+"]"+".Destination";
You can't access the ViewBag using above statement, since it accessible on server side. Your JavaScript statement is executed on the client side and can't directly access it.
However, You can use Json.Encode Method converts a data object to a string that is in the JavaScript Object Notation (JSON) format.
var jsObject = #Html.Raw(Json.Encode(ViewBag.AmritsarList));
$(".AClick").click(function () {
var s = parseInt($(this).attr('id'));
var neededVAl = jsObject[s].Destination;
alert(neededVAl);
$(this).attr("placeholder",neededVAl);
});
I'm serializing my model:
<script type="text/javascript">
var Model = '#Model.ToJson()';
</script>
the ToJson is an extension method:
public static string ToJson(this object obj)
{
var serializer = new JavaScriptSerializer();
var val = serializer.Serialize(obj);
return val;
}
Now I want to access my model in other javascript files by doing:
var hello = Model.id;
The problem is that it doesn't serialize correctly when I use '#Model.ToJson()' because of the quotes.
The serialized object looks like this:
var Model = "{ "id": "2231f87c-a62c-4c2c-8f5d-b76d11942301" }";
But in order for me to access id by Model.id it should look like this:
var Model = { "id": "2231f87c-a62c-4c2c-8f5d-b76d11942301" };
How can I enter razor syntax without quotes? Using asp.net syntax I think it's:
var Model = <%=Model.ToJson() %>
How do I do the same with razor? Thanks!
If you use this JSON plugin you can do it all on the client and simply things. If you push up a JSON string, in javascript you could then do:
<script type="text/javascript">
var Model = JSON.parse("#Model.JsonString");
</script>
Since Razor by default escapes out the quotes, you need to use Html.Raw:
var Model = #Html.Raw(Model.ToJson());
It will turn that into:
var Model = {"id":"whatever"};
which is valid javascript.
I am intentionally trying NOT to use a binding in the controller parameter, so I have a controller that looks like:
[HttpPost]
public ActionResult UntypedForm(String serializedformdata)
{
//// ...
}
When I post serialized JSON form elements to the controller with the below code:
var formelements = $('#form').serializeArray();
$.post(url, formelements, function (data) {
}, "json").error(function () {
alert("Error posting to " + url);
});
I get a NULL value for String serializedformdata on my controller. However, when I replace String serializedformdata with a strongly-typed object, binding works properly as expected.
The whole point of my controller is generic JSON posts, where I will create a BSON document to place into a Mongo database. SO....I intentionally DO NOT want model binding and I want the serialized string as pamameter. Why is my serializedformdata string null when I post?
Note - I also tried to bind to Dictionary with
public ActionResult UntypedForm(Dictionary<string,string> serializedformdata)
{
//// ...
}
but serializedformdata is still null.
The function serializeArray creates a Javascript object with the form's key/value pairs. You don't want that, you want a single key/value with serializedformdata = (JSON string). Ie, like this;
var formelements = { serializedformdata: JSON.stringify($('#form').serializeArray()) };
This passes the raw JSON string to the controller's parameter. You can use the JavaScriptSerializer to get the object on the server:
var obj = (List<Dictionary<string,string>>)new JavaScriptSerializer().Deserialize(serializedformdata, typeof(List<Dictionary<string,string>>));
Dictionary<string,string> dict = obj.First();
string someval = dict["somekey"];
I am trying, and struggling, to send an array via JSON to a MVC controller action.
Here is what I have and what i've tried...
//Get checked records
var $checkedRecords = $(':checked'); //e.g. 3 rows selected = [input 4, input 5, input 6]
//Have tried following:
sendingVar: $checkedRecords.serializeArray(); // gives array of 0's
sendingVar: JSON.stringify($checkedRecords); // gives "{\"length\":1,\"prevObject\":{\"0\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"length\":1},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"selector\":\":checked\",\"0\":{}}"...wtf
//Post
$.post(url, { sendingVar: sendingVar }, function(data) {alert(data); });
How do I do it ?
edit: to those that suggest sending $checkedRecords "as is" from the top line - that is not working. I get a strange exception somewhere in the jquery framework :(
uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://.../.../.../jquery-1.4.4.min.js :: <TOP_LEVEL> :: line 141" data: no]
which I think means it is attempting to assign null to something it cannot.
Edit: i'm using MVC2 not 3
Edit2: After #Monday's answer- the problem is due to how I have built the array like [input 4, input 5, input 6] and not [4,5,6] - any ideas how I can just get the values in the array instead ?
Edit3: Stop voting up duplicate when it's not. Did you actually read my problem or read the problems linked? this is a different issue
#Daveo:
I don't want to build in an overriding custom attribute just to send an array from JSON, that is rediculous as we've already covered in this question-it is not necessary.
MVC3 - irrelevant
Here is my demo,use mvc2,hope some helps~
The key to success is traditional
set the traditional parameter to true
$(function(){
var a = [1, 2];
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/Home/PostArray/") %>",
data: {orderedIds: a},
dataType: "json",
traditional: true,
success: function(msg){alert(msg)}
});
})
Since jquery 1.4 this parameter exists because the mechanism to serialize objects into query parameters has changed.
and action is~
[HttpPost]
public ActionResult PostArray(int[] orderedIds)
{
return Content(orderedIds.Length.ToString());
}
you can also use JSON.stringyfy to sent the data as a string then use JavaScriptSerializer class to retrive the data.
In C# code, to get the data, will look like this:
JavaScriptSerializer js = new JavaScriptSerializer();
js.Deserialize<T>(string paramiter);
use this simple code
var url = '/sampleController/sampleAction'
var params = {sendingVar: [1,2]}
$.post(url, params , function (data) {
$("#lblResult").html(' : ' + data);
}).fail(function (e) {
alert(e);
});