How to Read System.GUID on C# - c#

Here's my controller action
[HttpGet]
public JsonResult GetOrderNum(String input)
{
AEntities db = new AEntities();
var result = from r in db.orders
where r.TrackingNumber.ToString() == input
select new {
r.Status,
};
return Json(result, JsonRequestBehavior.AllowGet);
}
And here I make the AJAX call
var myActionUrl = '#Url.Action("GetTrackingNumber", "ACustomer")';
var trackingInfo = $('#TrackingNumber').val();
$('.Track').click(function () {
$.ajax({
type: "GET",
url: myActionUrl,
data: $('#TrackingNumber').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
alert("Response as JS Object: " + json);
console.log(json);
}
});
the problem is that it wont read the r.TrackingNumber.ToString() as it is system.guid. Any idea how I can resolve this?
At the moment when I run it, I just get an empty array "[]".

There are a number of different ways that a GUID can be represented as a string.
System.Guid.ToString() provides an overload with a format specifier. Select a format specifier that matches the format of the GUID found in input.
UPDATE
'System.String ToString()' method, and this method cannot be translated into a store expression
You will need to instead create a GUID from input:
Guid inputGuid = Guid.Parse(input);
var result = from r in db.orders
where r.TrackingNumber == inputGuid
select new {
r.Status,
};

Change the method public JsonResult GetOrderNum(String input) to read public JsonResult GetOrderNum(Guid input) thus passing the parameter as a GUID. Then there is no need to convert the data store GUID.

function FunctionName(Input) {
$.ajax({
type: 'GET',
url: '/GetOrderNum?Input=' + Input=', // Your URL Here
data: $('#TrackingNumber').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
alert("Response as JS Object: " + json);
console.log(json);
}
});
}
[HttpGet]
public JsonResult GetOrderNum()
{
string input =HttpContext.Current.Request["Input"].ToString();
Guid input= Guid.Parse(input);
AEntities db = new AEntities();
var result = from r in db.orders
where r.TrackingNumber.ToString() == input
select new {
r.Status,
};
return Json(result, JsonRequestBehavior.AllowGet);
}

Related

Run LINQ query with date range check in C# with correct date format

I am getting trouble in running LINQ query and I strongly believe is because of date format. I am getting string values for dates and other tags in ASP.NET C# code-behind webMethod from $ajax jQuery function and I am converting string date to Convert.ToDateTime. Date been selected on web-page using jQWidget and format is coming as in following screen shot of alert
and following screen shot of code-behind debugging
Ajax jQuery Function
$("#ctl00_ContentArea_btnFilterStudent").click(function (e) {
e.preventDefault();
var givenDateFrom = $("#CldBoxStudentFilter_From").jqxDateTimeInput('getDate');
var givenDateTo = $("#CldBoxStudentFilter_To").jqxDateTimeInput('getDate');
if(givenDateFrom && givenDateTo)
{
var selectedFilteredValue = $("#<%=ddLStudentFilterList.ClientID%> option:selected").val();
$.ajax({
url: 'TutorForm.aspx/FilterStudentListInRelationToStaffByDateRange',
type: "POST",
data: JSON.stringify({ GivenStaffID: SelectStaffID, SelectFilterOption: selectedFilteredValue, FromDate: givenDateFrom, ToDate: givenDateTo }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("success");
},
failure: function (response) {
alert(response.d);
}
}).done(function (response) {
});
C# code
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string FilterStudentListInRelationToStaffByDateRange(string GivenStaffID, string SelectFilterOption, string FromDate, string ToDate)
{
string returnList = string.Empty;
bool StudentStaffRelationActive = false;
List<StudentInRelationToStaffModelView> studentStaffRelationObject = new List<StudentInRelationToStaffModelView>();
//var queryList = StaffRelay.GetStudentsForRelationship(Convert.ToInt32(GivenStaffID), Convert.ToDateTime(FromDate), Convert.ToDateTime(ToDate), RelationshipStatus.None);
if (SelectFilterOption.Equals("StudentFilterSelectAll"))
{
var queryList = StaffRelay.GetStudentsForRelationship(Convert.ToInt32(GivenStaffID), null, null, RelationshipStatus.None);
var x = (from b in queryList
where b.RelationshipDateStart >= Convert.ToDateTime(FromDate) && b.RelationshipDateEnd <= Convert.ToDateTime(FromDate)
select b).ToList();
//need help here......
Looks like a time zone issue - client side +1 hour adjusted. You may have to specify the time zone of the date you are expecting on the server side.
DateTime rawDate = Convert.ToDateTime(matchFromXmlSoccer.Date);
TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTime targetDateTime = TimeZoneInfo.ConvertTime(rawDate, est);

Sql Table values in JSON c#

Hi i have a table with following values
Country Count
China 2
India 3
Pakistan 3
i want these in JSON as "China" : 2,"India" : 3,"Pakistan" : 3
I don't want the header Count and Country. I Have tried using ajax and HTTP Handler but no avail
$(document).ready(function () {
$.ajax({
url: 'CountryRegistrations.ashx',
type: 'POST',
dataType: 'json',
success: function (data) {
var test = data.Country + data.Count;
alert(test);
},
error: function (data) {
alert("Error");
}
});
});
public void ProcessRequest(HttpContext context)
{
FilterCountry emp = getCounts();
// serialize and send..
JavaScriptSerializer serializer = new JavaScriptSerializer();
StringBuilder sbJsonResults = new StringBuilder();
serializer.Serialize(emp, sbJsonResults);
context.Response.Clear();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(sbJsonResults.ToString());
}
private FilterCountry getCounts()
{
FilterCountry fc = new FilterCountry();
fc.Country = "PK";
fc.Count = 600;
return fc;
}
I gives me as PK600 but it should give "PK":600 and how to get these values from database right now im trying to get from hard coded values.
var test = data.Country + data.Count;
Try to change to:
var test = data.Country + ':' + data.Count;
If you are using JavaScriptSerializer then it will will serialize the object in to JSon format like "Key":"Value" that is also based on the object you are passing to Serialize method.
Your class "FilterCountry" has two property "Country" and "Count" and assigning values on it.
So it will be serialize like as follows { "Country" : "PK", "Count":600 }
Please go through JSon and serialize examples

How to pass Js array object with normal object collection to controller in ajax post 'html' datatype

I have the collection of string and array variable which is need to pass controller through ajax post action. for Ex:
string str="john";
int temp= 10;
var arrayObj=new Array();
$.ajax({
type: 'Post',
url: 'home/controller',
data: ?, // how to pass all string,int and array object
datatype: ?, //'html/ or Json' what will need to give?
success: function (result) {
},
});
Anyone could answer my questions?
Thanks,
Bharathi.
Without seeing your controller method:
var str="john";
var temp= 10;
var arrayObj = [somevar, somevar2];
$.ajax({
type: 'Post',
url: 'home/controller',
data: {nameParameter: str, tempParameter: temp, arrayParameter: arrayObj},
contentType: 'text',
/* dataType: , depends on what your controller method returns */
success: function (result) {
}
});
The other option is to use JSON2 library (NuGet).
'data' would now use
JSON.stringify({ nameParameter: str, tempParameter: temp, arrayParameter: arrayObj })
The contentType should then change to application/json

Can a json object's value and key be set in controller action in MVC?

Is it possible for me to get the same SelectListItems in this list:
public static List<SelectListItem> GetAreaApprovingAuthorities(int id)
{
List<Employee> approvingAuthorities = new List<Employee>();
using (var db = new TLMS_DBContext())
{
approvingAuthorities = db.Employees.Where(e => e.UserRoleID > 1 && e.PersonnelAreaID == id).ToList();
}
List<SelectListItem> returned = new List<SelectListItem>();
foreach (Employee emp in approvingAuthorities)
{
returned.Add(new SelectListItem { Text = string.Format("{0} {1}", emp.FirstName, emp.LastName), Value = emp.ID.ToString() });
}
return returned;
}
and pass them into a select list using Json?
Here is the controller action where the List is acquired:
public JsonResult GetApprovingAuthorities(int id)
{
return Json(TLMS_DropDownLists.GetAreaApprovingAuthorities(id),JsonRequestBehavior.AllowGet);
}
Here is where the json object is iterated through and then passed to the select list (this is triggered when another select list's value is changed):
$.ajax({
type: 'GET',
data: { id: selectedValue },
url: '#Url.Action("GetApprovingAuthorities")',
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
success: function (jsonObj) {
$('#aa').empty();
$.each(jsonObj, function (key, value) {
$('#aa').append($("<option/>", {
value: key.Text,
text: value.Text
}));
});
}
});
This is working to populate the "aa" select list and I am receiving the select list's selected item via the FormCollection in a controller action, but I cannot capture the original ID from the "GetAreaApprovingAuthorities" SelectListItem's Value. Is there a way that I can make this happen?
When you're iterating on the jsonObj it should be like this
//the first parameter is just the index of the iteration
//and the second one is the json object (SelectListItem)
$.each(jsonObj, function (index, obj) {
$('#aa').append($("<option/>",
{
value: obj.Value,
text: obj.Text
}));
});

How to a Deserialize Json object made by JavaScriptSerializer from a List in jQuery/Javascript

Okay I am serializing a bunch of years from a database call into a json object.
This object is the response from the webservice to the first ajax call. My javascript error console throws an error on the line where it is suppose to deserialize it. I am trying to figure out what is wrong.
Update:
This code works, thanks to Jussi Kosunen
$.ajax(
{
type: "POST",
url: "default.aspx/HelloWorld",
dataType: "json",
data: "{name:'" + name + "'}",
contentType: "application/json; charset=utf-8",
success: function (msg) {
//parse the object into something useable.
var stringarray = JSON.parse(msg.d);
//empty the results for next time around.
$('#year').empty();
for (index in stringarray) {
$('#year').append('<option>' + stringarray[index] + "</option>");
alert(stringarray[index]);
}
This is the C# that serialized the list into an json object;
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static string HelloWorld(string name)
{
string splitme = "USE VCDB SELECT DISTINCT YearID FROM BaseVehicle";
DataTable dt = getDataTable(splitme);
List<string> ids = new List<string>();
foreach (DataRow row in dt.Rows)
{
ids.Add(row.ItemArray[0].ToString());
}
JavaScriptSerializer js = new JavaScriptSerializer();
string x =js.Serialize(ids);
return x;
}
Now when I go into debug. this is the string the C# is returning.
[\"1896\",\"1897\",\"1898\",\"1899\",\"1900\",\"1901\",\"1902\",\"1903\",\"1904\",\"1905\",\"1906\",\"1907\",\"1908\",\"1909\",\"1910\",\"1911\",\"1912\",\"1913\",\"1914\",\"1915\",\"1916\",\"1917\",\"1918\",\"1919\",\"1920\",\"1921\",\"1922\",\"1923\",\"1924\",\"1925\",\"1926\",\"1927\",\"1928\",\"1929\",\"1930\",\"1931\",\"1932\",\"1933\",\"1934\",\"1935\",\"1936\",\"1937\",\"1938\",\"1939\",\"1940\",\"1941\",\"1942\",\"1943\",\"1944\",\"1945\",\"1946\",\"1947\",\"1948\",\"1949\",\"1950\",\"1951\",\"1952\",\"1953\",\"1954\",\"1955\",\"1956\",\"1957\",\"1958\",\"1959\",\"1960\",\"1961\",\"1962\",\"1963\",\"1964\",\"1965\",\"1966\",\"1967\",\"1968\",\"1969\",\"1970\",\"1971\",\"1972\",\"1973\",\"1974\",\"1975\",\"1976\",\"1977\",\"1978\",\"1979\",\"1980\",\"1981\",\"1982\",\"1983\",\"1984\",\"1985\",\"1986\",\"1987\",\"1988\",\"1989\",\"1990\",\"1991\",\"1992\",\"1993\",\"1994\",\"1995\",\"1996\",\"1997\",\"1998\",\"1999\",\"2000\",\"2001\",\"2002\",\"2003\",\"2004\",\"2005\",\"2006\",\"2007\",\"2008\",\"2009\",\"2010\",\"2011\",\"2012\",\"2013\"]
As you're passing dataType: "json" into your $.ajax call, it's parsing your JSON automatically.

Categories

Resources