I have some thing like this.."Skin','Hair"...
i want result like this ['Skin', 'Hair'];
I tried this
type: 'GET',
url: '/HOME/Getselecteddata',
dataType: 'json',
data: { id: 8 },
success: function (data) {
debugger;
var endString = data.replace(/"/g, "'");
var selectedCodeWBs = [data]
$(".tokenizationSelect2").val(selectedCodeWBs).trigger('change');
Not working. please someone help me
my controller code:
public ActionResult Getselecteddata(int id)
{
var data = db.Segments.Where(x => x.Id == 7003).Select(x => x.Segname).SingleOrDefault();
List<string> segmentdata = new List<String>(data.Split(','));
string s2 = String.Join("','", segmentdata);
return Json(s2, JsonRequestBehavior.AllowGet);
}
You can much better do this:
return Json(segmentdata, JsonRequestBehavior.AllowGet);
Using segmentdata directly will work 100% better than creating a messy string variable that contains unbalanced quotes.
MVC Json() is perfectly capable of working with a List, it will output it as JSON array notation. Then in your javascript the received value in data will already be a Javascript array that won't need further manipulating.
Related
The function getClientData() gets called from one of the anchor tags in a grid's column. The anchor tag has a couple of Data-Tags which are passed to the code behind method. I have to perform some DB operation through these parameters but before that I wanted to make sure if this prototype would work.
This is how the anchor tag looks:
Show
This is my Javascript method:
function getClientData() {
//var dataValue = { "keyData": this.event.target.getAttribute("data-kt"), "valueData": this.event.target.getAttribute("data-kv")};
$.ajax({
type: "GET",
url: "Clients.aspx/GetClientData",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ keyData: this.event.target.getAttribute("data-kt"), valueData: this.event.target.getAttribute("data-kv")}),
dataType: 'json',
error: function (error) {
alert(error.statusText);
},
success: function (result) {
alert("Success: " + result );
}
});
}
I put a break point here and it never gets triggered. This is my web method in the code behind file:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string keyData, string valueData)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}
This is the URL that gets created for the POST request "http://localhost:60825/Clients.aspx/GetClientData?{%22keyData%22:%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22,%22valueData%22:%221p7q9%22}". Please let me know if I am doing something wrong.
I am not sure how you configured routing but based on your API method (code behind) your data should be formatted in following manner:
Method 1:
http://localhost:60825/Clients.aspx/GetClientData?keyData=Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy&valueData=1p7q9
As you can see, instead passing stringified JSON object I am sending data in format of query string where keyData and valueData has corresponding values.
Method 2:
If you prefer to send stringified JSON you can modify your Payload in URL like this:
http://localhost:60825/Clients.aspx/GetClientData?data=%7BkeyData%22%3A%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22%2C%22valueData%22%3A%221p7q9%22%7D
Here I am sending stringified JSON as data parameter in query string. For that purpose your code behing method needs to be like this:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string data)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}
I post some via AJAX in my servet from my jsp
$.ajax({
url: 'myServlet?action=FEP',
type: 'post',
data: {machine: i, name: txt}, // i, txt have some values.
success: function (data) {
alert('success');
}
});
and in my Serlvlet
String jspAction = request.getParameter("action");
//...
if(jspAction.equals("FEP")){
int idMachine = Integer.parseInt(request.getParameter("machine"));
String name = request.getParameter("name");
double value = actions.getValue(idMachine, name); //<-- this variable I want to send it back to the JSP.
}
The data are sent succesfully. However I haven't understand how I send back the vaule to the jsp..
returning a string would go as follows:
response.getWriter().write("a string");
return null;
If you want to return json, you can use many libraries like: http://www.json.org/
This would result in something like following code:
response.setContentType("application/json");
JSONObject jsonObject = new JSONObject();
double aDouble = 38d;
jsonObject.put("returnValue", aDouble);
response.getWriter().write(jsonObject.toString());
return null;
Use
response.getWriter().write(value);
return null;
And in your ajax success block access the value.
See the following link for more understanding http://www.javacodegeeks.com/2014/09/jquery-ajax-servlets-integration-building-a-complete-application.html
I have this Index action:
public ActionResult Index()
{
var repo = (YammerClient) TempData["Repo"];
var msgCol = repo.GetMessages();
ViewBag.User = repo.GetUserInfo();
return View(msgCol.messages);
}
GetMessages returns a list of POCO messages and GetUserInfo returns a POCO with the info of the user (id, name, etc).
I want to fill a javascript variable with the JSON representation of the user info.
So I would want to do something like this in the view:
...
<script>
var userInfo = "#ViewBag.User.ToJson()"
</script>
...
I know that doesn't work, but is there a way to do that? I want to avoid having to do an ajax request once the page is loaded just to get the user info.
In View you can do something like this
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var userInfoJson = jss.Serialize(ViewBag.User);
}
in javascript you can use it as
<script>
//use Json.parse to convert string to Json
var userInfo = JSON.parse('#Html.Raw(userInfoJson)');
</script>
Was using this solution for simple objects. But I had some problems getting an array to js objects so I'll just leave what I did here.
C#
#{
using Newtonsoft.Json;
ViewBag.AvailableToday = JsonConvert.SerializeObject(list);
}
js
var availableToday = JSON.parse('#Html.Raw(ViewBag.AvailableToday)');
Client-Side Code:
This is an ajax call to a .Net MVC Controller:
var clientStuff;
$.ajax({
type: 'GET',
url: '#Url.Action("GetStuff", "ControllerName")',
data: {},
dataType: "json",
cache: false,
async: false,
success: function (data) {
clientStuff = data;
},
error: function(errorMsg) {
alert(errorMsg);
}
});
Server-Side Code:
CONTROLLER:
public JsonResult GetStuff()
{
return Json(_manager.GetStuff(), JsonRequestBehavior.AllowGet);
}
MANAGER:
public IEnumerable<StuffViewModel> GetStuff()
{
return _unitofWork.GetStuff();
}
UNIT OF WORK:
public IEnumerable<StuffViewModel> GetStuff()
{
var ds = context.Database.SqlQuery<StuffViewModel>("[dbo].[GetStuff]");
return ds;
}
Unit of Work can be a query to a sproc (as I have done), a repository context, linq, etc.
I'm just calling a sproc here for simplicity, although it could be argued that the simplicity lies with Entity Framework and Linq.
You can change this line :
ViewBag.User = repo.GetUserInfo();
To
ViewBag.User = new HtmlString(repo.GetUserInfo());
You should add using Microsoft.AspNetCore.Html; or using System.Web; if HtmlString is not accessible.
timeline.js + MVC + Ajax + JSON
hello,
I have problem while converting string to Json Object
I have to display timeline on my webpage, I have used Timeline.js for the same, I am able to run the timeline using static data that is as following
Static Data
// Create a JSON data table
data = [
{
'start': new Date(2010, 7, 23),
'content': 'Conversation'
},
{
'start': new Date(2010, 7, 23),
'content': 'New Conversation'
},
{
'start': new Date(2010, 7, 23),
'content': 'Very New Conversation'
}
now when I do
alert(data);
it gives me
[object Object],[object Object],[object Object]
but now I have to display a data from the DB, so I am calling the following function on controller
GetTimeLine method on controller
public JsonResult GetTimeline()
{
JsonResult jr = new JsonResult();
var objtimeline = objEntities.Timelines.Where(tl => tl.StudentID == Sessions.StudentID).ToList().AsQueryable();
String newstr = "[";
foreach(var tml in objtimeline)
{
DateTime date1 = Convert.ToDateTime(tml.CalculatedDate);
newstr += "{'start': new Date("+date1.Year+","+date1.Month+","+date1.Day+","+date1.Hour+","+date1.Minute+","+date1.Second+"),'content':'"+tml.Description+"'},";
}
newstr = newstr.TrimEnd(',');
newstr += "];";
jr.Data = newstr;
jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jr;
}
function to call controller method
jQuery.ajax({
type: "POST",
url: "#Url.Content("~/Student/GetTimeline")",
success: function (result) {
data = result;
},
});
alert(data);
it gives me the following alert
[{'start': new Date(2012,2,11,0,0,0),'content':'Parents meeting'},{'start': new Date(2012,2,15,0,0,0),'content':'Exam Meeting'}];
so the problem is with conversion of string to Json Object,
How can I convert string returned from controller to Json Object on my view...
You're working too hard. Let the framework do it for you.
public JsonResult GetTimeline()
{
var timeline = objEntities.TimeLines.Where( tl => tl.StudentID == Sessions.StudentID )
.ToList() //required due to Convert call
.Select( tl => new
{
start = Convert.ToDateTime(tl.CalculatedDate),
content = tl.Description
});
return Json( timeline, JsonRequestBehavior.AllowGet );
}
Then either use getJSON (since you specifically allow gets) or specify dataType: 'json' in your request.
$.getJSON( '#Url.Action("gettimeline","student")', function(data) {
alert(data);
});
What you have the server returning is not valid JSON. Or give your server-side code, it may be valid JSON which just defines a string rather than an object graph. In JSON:
All object keys must be in double quotes, not single quotes.
All strings must be in double quotes, not single quotes.
new Date(...) is not valid (JSON doesn't have any concept of dates).
I believe you want to build up an array (not a string) and assign that to jr.Data, and then let the JsonResult object handle the serialization for you (but I haven't done this in ASP.net MVC).
Once you have the server returning valid JSON, ensure that it's returning it with the correct Content-Type header (the value is application/json). When you do, jQuery will see that it's JSON and deserialize it into an object graph for you. If you can't or don't want to make your server return valid JSON, add dataType: 'json' to the ajax call to force it.
Im constructing an array of objects like this:
var postData = [];
$.each(selectedFields, function (index, value) {
var testTitle = 'testing ' + index;
postData.push({title: testTitle, title2 : testTitle});
}
I then post it like this(note that i have tried a number of different aproaches):
$.post('SaveTitlesHandler.ashx', { form : postData }, function (data) {
console.log(data);
});
I then try to get the data in a handler...
public class SaveTitlesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string json = context.Request.Form.ToString();
}
}
I cant seem to get proper json out of the request. Anyone got any idea?
cheers.
twD
You are not posting JSON. You are using application/x-www-form-urlencoded. So inside the handler you could access individual values:
public void ProcessRequest(HttpContext context)
{
var title1 = context.Request["form[0][title]"];
var title2 = context.Request["form[0][title2]"];
var title3 = context.Request["form[1][title]"];
var title4 = context.Request["form[1][title2]"];
...
}
If you wanted to POST real JSON you need this:
$.ajax({
url: 'SaveTitlesHandler.ashx',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(postData),
success: function(result) {
console.log(result);
}
});
and then inside the handler read from the request input stream:
public void ProcessRequest(HttpContext context)
{
using (var reader = new StreamReader(context.Request.InputStream))
{
string json = reader.ReadToEnd();
}
}
The JSON.stringify method converts a javascript object into a JSON string and it is a native method built-in modern browsers. You might also need to include json2.js if you want to support older browsers.