jQgrid edit form dropdown list has extra quote - json

I have an MVC2 EditStatesController :
public JsonResult GetStates()
{
string statesToReturn = GetStates(); // returns "1: Alabama; 2: Alaska; 3: Arizona; 4: Arkansas"
return Json(statesToReturn);
}
this is the code that calls the controller:
//get States
var listOfStates = $.ajax({
url: '/EditStates/GetStates',
type: 'POST',
async: false,
success: function(data, result) {
if (!result)
alert('Failure to retrieve States.');
}
}).responseText;
The dropdown has the list of elements, but last element has extra " (double quote), so the last state Wyoming is Wyoming".
I searched other questions, but didn't find a similar one. Do you know why this is happening and how to fix this?
Thank you,
Jenny

The searchoptions can use dataUrl and optionally buildSelect instead of value which you try to use currently.
jqGrid need to construct the HTML fragment like the following:
<select>
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
</select>
So you can either provide the data from an action of your controller directly or provide any other output like JSON output:
[
{"id":1, "name":"Alabama"},
{"id":2, "name":"Alaska"},
{"id":3, "name":"Arizona"},
{"id":4, "name":"Arkansas"}
]
and use buildSelect event handler to convert the JSON data to the HTML fragment with <select>...</select>. See the answer for details.
If you choose the way you will have no problems with any special characters like '"', ':', ';' and so on.

Related

knockout's viewModel does not get updated

I have the following knockout's viewModel :
var viewModel={
businessName: "",
....
}
I also tried to identify the field like this: businessName: ko.observable("")
Then, I have a load method that requests for a JSon with a newly populated data
And this is how I'm trying to apply the new data:
$.ajax({
//
url: "#Html.Raw(#Url.Action("Load"))",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
//OPTION 1:
viewModel.businessName = result.vm.BusinessName;
//OPTION 2:
var viewModel2 = ko.mapping.fromJS(result.vm);
console.log(viewModel2.businessName);
}
});//ajax
As a result:
if I use Option1, I get the new data but it does not get updated on the page.
If I use Option2, it writes "undefined"
Please advise how can I update the new data on the page?
I checked the similar topics but there is no answer that helps
PS
It seems I resolved OPTION 1. But still don't understand why OPTION 2 does not work
ko.observable is a function, not a property. So you get it's value like this:
var whatsTheValue = myVM.MyObservable();
and you set it like this:
myVM.MyObservable(newValue);
This is all in the docs.
Note, however, when using the data-bind syntax in your HTML, you don't need to explicitly unwrap your observable by using the parenthesis because KO is smart enough to do it automatically:
<span data-bind="text: MyObservable"></span>
You have to use ko.observable in the ViewModel and access/write it accordingly.
var myViewModel = {
businessName = ko.observable('')
};
...
$.ajax({
...
success: function(result) {
myViewModel.businessName(result.vm.BusinessName);
},
...
});
Otherwise your view won't have any clue you changed businessName. In the implementation ko.observable, besides actually storing the new value, broadcasts some events to your view, letting it know the stored value changed.

jQuery <select> Changes Another <select>

I am using trying to use jQuery .change() to create two <select> elements whereby the first <select id="state"> is for generating a list of states and the second <select id="city"> is to generate a list of cities.
The values of states and cities will not be hard-coded but generated from values pass from web services.
The list of options to be generated is supposed to work like this: if user selects state from <select id="state"> the selected value will be pass to a web service to retrieve the list to generate the <select id="city"> for cities.
I'm really not sure how to implement this. Can anyone please advise me?
it should look something like
$(function(){
// populate the states list from Ajax
$.ajax( {
url:"/listStates",
type:"GET",
success:function( data ) {
var statesList = data;
if ( typeof(data) == "string" ){
statesList = JSON.parse(data);
}
$.each( statesList, function( index, state ){
$("#state").append($("<option></option>",{value:state.value, text:state.label});
});
},
error:function( result ) {
console.log(["error getting states",result]);
}
});
// register on state list change
$("#state").change( function(){
// on change dispatch an AJAX request for cities and populate cities
$.ajax({ url : "/listCities",
data : {"state": $("#state").val() },
type:'GET',
success:function( data ) {
var citiesList = data; // assuming list object
if ( typeof(data) == "string"){ // but if string
citiesList = JSON.parse( data );
}
$("#city").empty();
$.each(citiesList, function(index,city){
$("#city").append($("<option></option>", {"value":city.value, "text":city.label}));
}
},
error:function( result ){ console.log(["error", result]); }
})
});
This can get you started however I did not follow lint best practices here.
Walk Through
I register for a "change" event on select with id state.
When a change if fired, I invoke an Ajax request to location "/listCities"
I assume this location is called with a "GET" method
I pass along the state that is currently selected - so the server will know which cities to list.
If the Ajax through an error, I log the error to the console.
If the Ajax was a success, I populate the select with id "city" with options containing values for each city and a label.
I assumed the following things while writing the code
You have a route GET /listCities that expects a state.
The response from that route is a JSON containing a list of values and labels for each city. Something like this :
[{ value : "AM" , label : "Amsterdam" }, .... ]
The only things you may need to read about for this example are :
JQuery Ajax Calls
Best Practice To Populate A List With JQuery
If you have any questions, please comment my response, I will be happy to explain/add/modify
You have to follow some steps achieving this:
first when page load populate the first country list via ajax (my assumption)
then create a .change() event with the country list
This will send a request and returns the states list response as per selected country.
you can try test it this way:
$(function(){
$.ajax({
url:your url,
type: 'post',
dataType: 'json', // or your choice of returned data
success: function(data){
$.each(data, function(i, v){
$('<option value="'+v.name+'">'+v.text+'</option>').appendTo('#country');
});
}
});
$('#country').change(function(){
$.ajax({
url:your url,
type: 'post',
dataType: 'json', // or your choice of returned data
success: function(states){
$.each(states, function(i, stt){
$('<option value="'+stt.name+'">'+stt.text+'</option>').appendTo('#states');
});
}
});
$('#states').empty();
});
});
Pretty simple - all you'll have to do is have the two dropdowns, one with the full lists of states and the second (empty) city list will contain only one blank disabled option.
As soon as your states dropdown triggers a change event, you extract the state data and send it via an AJAX call to your server or some web service which will return a list of cities in that state.
You'll then populate the second dropdown with the returned city values.

Array of integers as value for an option in a html select

i have a question about the <option> of a <select> tag in my mvc3 c# application.
Can i pass an array of ints to an action using a <option> tag?
I mean, something like this:
<select name="status_filter">
<option value="1,2,3,4">All</option>
<option value="2,3">Some</option>
<option value="2">One</option>
</select>
and in my action method:
public ActionResult Filter(int[] status_filter)
Can be done?
Thanks,
Gonzalo.
By default this will not bind. You will need a custom model binder OR pass it as an array in javascript
From:
in asp.net mvc, how can I pass an array of integers as a parameter
$.ajax({
url: '#Url.Action("Refresh", "Calendar")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ scope: scope, scopeId: scopeId }),
success: function(result) {
// ...
}
});
Or use your own model binder:
http://neimke.blogspot.com/2011/01/pass-array-of-integers-to-controller.html
Finally i have to change the array for a string that say's "all", "some", "one" and then on the controller perform a switch.

Passing JSON object to MVC Controller

I can successfully make a jQuery Ajax call into my C# Controller and receive back an XML string, but I need to in turn gather some Portfolio dates and package them up into a JSON object so I can send them back into another C# Controller.
If it's a C# issue, then I apologize if I'm in the wrong forum...however I'd like to pass my JSON object into the server side controller ..
Here's what I'm trying to do:
var nodeDatesJson = {"nodedates": // CREATE JSON OBJECT OF DATE STRINGS
{ "date": 01/20/2012,
"date": "01/21/2012" } };
getTradeContribs(thisPfId, nodeDatesJson.nodedates.date);
Now call the next js function:
function getTradeContribs(pfid, nodedates) {
//alert(nodedates);
$.ajax({ // GET TRADE CONTRIBS FROM SERVER !!
url: "/Portfolios/getTradeContribs?portfolioId=" + pfid + "&nodedates=" + nodedates,
type: "GET", // or "PUT"
dataType: "json",
async: true,
success: parseTradeContribs,
error: function (error) {
alert("failed in opening Trade Contribs file !!!");
}
});
}
function parseTradeContribs(data) {
alert("In parseTradeContribs..." );
$(data).find("Trade").each(function(){
$(".TradeContrib").append($(this).text());
})
}
and my C# controller is trying to read in the "nodedates" JSON object, but HOW do I read it in ?
public string getTradeContribs(string portfolioId, **string nodedates**)
{
// Build Portfolio Select request here !
RequestBuilder rzrRequest = new RequestBuilder();
// REQUEST FOR CONTRIBUTIONS !
// ... more code here..
xmlResponse.LoadXml(contribResponse);
string jsonTest = #" {""nodedates"": ""date"":""01/01/2012""}";
//return xmlResponse.OuterXml; // WORKS FINE
return "<Trade><TradeId>1234</TradeId></Trade>"; // RETURN TEST XML STR
}
thank you in advance...
Bob
The best way to receive a list of dates in a MVC action is to bind to a collection. What this means is that you should put your dates and other attributes in a form with the following naming convention:
<input type="hidden" name="dates" value="2012-1-20" />
<input type="hidden" name="dates" value="2012-1-21" />
Then you should serialize this form (look into jquery's docs for this) and post its data to your action, which will be something along the lines of:
public ActionResult getTradeContribs(string portfolioId, IList<DateTime> dates) {
// Do your work here
}
You should really take a look into MVC Model binding and collection binding as well:
Model binding to a list
Model binding objects
Also, if I may, your javascript object has two properties with the same name, which is probably not what you mean. If you want to have multiple dates stored somewhere in a object, you should use an array:
var nodeDatesJson = {"nodedates":
[ "01/20/2012", "01/21/2012" ] };
Sorry, but I didn't understand your doubt very well...but here it goes:
Maybe you should pass the json, well-formatted, as a string and use some C# parser.
This way you can get a object in server-side as same as the Json object in javascript.
=]

AJAX response using Jquery (with zend framework) contains unwanted HTML Code

Currently, the following code works as intended but if I add an echo such as "LANG: en" anywhere in the code (let's say in the bootstrap), the following code won't work anymore and I get this ajax request response :
<br/>LANG : en{"response":true,"id":13}
(the ajax response contains the echo + json array ) and therefore I'm not able to print the id (it will print : undefined when i will try to access to data.id).
My question is : How can I print my debug info and still manage to perform ajax requests ?
Here is my code in the controller :
public function init()
{
$this->_helper->ajaxContext->addActionContext('retrievecategories', 'json')->initContext();
}
public function retrievecategoriesAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isXmlHttpRequest()) {
if (isset($_POST['id']))
$id = $_POST['id'];
$id+=1;
echo json_encode(array('response' => true, 'id' => $id));
}
}
My js code :
jQuery(function(){
var obj = {"id":12};
jQuery.ajax({
url: '/search/retrievecategories?json',
type: 'post',
data: obj,
dataType: 'json',
success: function(data){
var id = data.id;
alert(id);
},
error: function(data){
var id = data.id;
alert(id);
}
});
});
I hope I was clear enough. Thank you for your time !
If you echo anything but the JSON object, the JQuery parser will fail because the response is no longer a valid JSON. you could make a custom parser which interprets the response text and takes away the debug info leaving the JSON object, or you can include the debug info in the array you encode.
json_encode(array('data'=>'data','debug'=>'debug info'))
Then you detect if the debug field is present and after a console.log() or alert() you delete it form the object.
I would strongly recommend that you read about firePHP. It uses the same console that Firebug uses to display debug information from your php code. It is really simple to use with the Zend_Log.