how to retrieve the json returned in a string variable in mvc4 vb.net - asp.net-mvc

how can I get the json being returned from mvc4 web platform
below is my function:
Public Function insertReg()
dim res as new resObj()
res.id=1
res.name="test"
return res
End Function
public class resObj
Public Property id As Integer
Public Property name As String
End Class
when I return the res object my mvc4 solution converts it directly to json, but I need to retrieve this json and put it in a variable for another use.

You can import the following Namespace, you will probably need to add the relevant assembly. And then you can serialize into a JSON string
import System.Web.Script.Serialization;
Public Function insertReg()
dim res as new resObj()
res.id=1
res.name="test"
var json = new JavaScriptSerializer().Serialize(res);
return res
End Function
If you want the root object to go along with the JSON than create a dynamic wrapper class.
TestModel model = new TestModel();
model.pass = "PassMe";
dynamic Wrapper = new
{
TestModel = model
};
var JSON = new JavaScriptSerializer().Serialize(Wrapper);
JSON will = {"TestModel":{"pass":"PassMe"}}

Related

Post request with body into a model

I had to implement it using javascript.
I have this class:
Public Class RecommendedJobsData
Public Property searchedJobsList As List(Of JobInfo)
Public Property jobFromStorage As JobInfo
Public Property totalJobsCount As Integer
Public Property adType As AdType
Public Sub New() ' default constructor
End Sub
' constructor with parameters
Public Sub New(searchedJobsList As List(Of JobInfo), jobFromStorage As JobInfo, totalJobsCount As Integer, adType As AdType)
Me.searchedJobsList = searchedJobsList
Me.jobFromStorage = jobFromStorage
Me.totalJobsCount = totalJobsCount
Me.adType = adType
End Sub
End Class
I am trying to send a post request to this function:
<JsonpFilter()>
Public Function GetToken(header As RequestHeader, body As RecommendedJobsData) As String
Return String.Empty
End Function
So I used javascript:
var http = new XMLHttpRequest();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {//Call a function when the state changes.
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(apiParams);
The header is passed fine, but the body is not..
It enters the default constructor instead of the constructor that gets parameters, and then, there are null values in the body object of GetToken function.
This is apiParams:
Any help appreciated!
I have changed the content-type to be:
http.setRequestHeader("Content-type", "application/json");
And then I changed the send function:
http.send(JSON.stringify(apiParams));
And the most important thing is:
<FromBody()> attribute in GetToken function:
Public Function GetToken(header As RequestHeader,
<FromBody()> body As RecommendedJobsData)
Note to add a reference to system.web.http.

How do I use OData $filter results on the server

I have a working OData controller, which supports all the normal get/put etc.
What I want to do is pass a normal odata $filter string from the client, parse and execute the filter on the server and run some code on the resulting IEnumerable.
I've messed around with ODataQueryContext, ODataQueryOptions, FilterQueryOption etc, but not really got anywhere.
Does anyone have any working examples?
Edit: I've added my function skeleton, just need to fill in the blanks
public HttpResponseMessage GetJobs(string filter)
{
*** How to convert the filter into IQueryable<Job> ***
var queryable = ?????
var settings = new ODataQuerySettings();
var jobs = queryOptions.ApplyTo(querable, settings) as IQueryable<Job>;
CsvSerializer csvSerializer = new CsvSerializer();
string csv = csvSerializer.Serialise(jobs);
string fileName = string.Format("{0} Jobs.csv", filter);
return CreateCsvResponseMessage(csv, fileName);
}
I recently had a scenario where I needed this sort of feature as well. This is what I came up with.
private static IQueryable<T> ApplyODataFilter<T>(IQueryable<T> data, string filterString) where T : class
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<T>(typeof(T).Name);
ODataQueryContext context = new ODataQueryContext(builder.GetEdmModel(), typeof(T), new ODataPath());
ODataQueryOptionParser queryOptionParser = new ODataQueryOptionParser(
context.Model,
context.ElementType,
context.NavigationSource,
new Dictionary<string, string> { { "$filter", filterString } });
FilterQueryOption filter = new FilterQueryOption(filterString, context, queryOptionParser);
IQueryable query2 = filter.ApplyTo(data, new ODataQuerySettings());
return query2.Cast<T>();
}
Try using OData code generator to generate client side code. you can following the following blog:
How to use OData Client Code Generator to generate client-side proxy class
The for the filter, the following is an example:
var q2 = TestClientContext.CreateQuery<Type>("Accounts").Where(acct => acct.Birthday > new DateTimeOffset(new DateTime(2013, 10, 1)));
There are some sample code in the codeplex to show how to do query.
Check this:
https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v3/ODataQueryableSample/Program.cs
Update:
There is some sample code in the controller of the sample I gave you.
Write your code as below:
public IQueryable<Order> Get(ODataQueryOptions queryOptions)
{
if (queryOptions.Filter != null)
{
var settings = new ODataQuerySettings();
var filterResult = queryOptions.ApplyTo(OrderList.AsQueryable(), settings) as IQueryable<Order>;
// Use the filter result here.
}
}
Update 2:
You can get the raw string of the filter from ODataQueryOptions.
public IQueryable<Order> Get(ODataQueryOptions queryOptions)
{
string filterString = queryOptions.Filter.RawValue;
// Use the filterString
}
Update 3:
(Note: ODataProperties is an extension method in static class
System.Web.Http.OData.Extensions.HttpRequestMessageExtensions)
public HttpResponseMessage GetJobs(string filter)
{
var context = new ODataQueryContext(Request.ODataProperties().Model, typeof(Job));
var filterQueryOption = new FilterQueryOption(filter, context);
IQueryable<Job> queryable = GetAllJobs();
var settings = new ODataQuerySettings();
var jobs = filterQueryOption.ApplyTo(queryable, settings) as IQueryable<Job>;
CsvSerializer csvSerializer = new CsvSerializer();
string csv = csvSerializer.Serialise(jobs);
string fileName = string.Format("{0} Jobs.csv", filter);
return CreateCsvResponseMessage(csv, fileName);
}

save form values through script file in umbraco

hello i want to save the value of umbraco form in database for this i have made script file and in this script file i have created function to save data and called this function in same script file and this script file is used in macro and i have called this macro in template of my page but it is not working will this approach is proper or i have to something else my basic aim is to save data in database without creating my usercontrol
code is
#functions
{
public void AddToCart()
{
string con = System.Configuration.ConfigurationManager.AppSettings["umbracoDbDSN"].ToString();
SqlConnection OnCon = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["umbracoDbDSN"].ToString());
ItemsDataContext db = new ItemsDataContext(con);
var request = HttpContext.Current.Request;
string itemcode= request.Form["ItemCode"].ToString();
string itemname = request.Form["ItemName"].ToString();
string itemcategory = Request.Form["ItemCategory"].ToString();
string userid = "Pallavi";
db.sp_AddItems(userid, itemcode, itemcategory, itemname, 0);
HttpContext.Current.Session["UserId"] = "Pallavi";
}
}
#if (!IsPost)
{
AddToCart();
}
and called this macro on template
<umbraco:Macro Alias="Uc_Cart" runat="server"></umbraco:Macro>
You approach is wrong. You must use the methods that Umbraco provides in their API and do not try to write data into the database directly.
Try this code to create an new document from Razor code:
#using umbraco.BusinessLogic;
#using umbraco.cms.businesslogic.web;
#{
DocumentType dt = DocumentType.GetByAlias("Textpage");
User author = umbraco.BusinessLogic.User.GetUser(0);
Document doc = Document.MakeNew("My new document", dt, author, parentID);
}
The example above is for Umbraco 4.x. If you're using Umbraco v6.x you could also use the new API methods:
#{
// get an instance of the contentService
var contentService = ApplicationContext.Services.ContentService;
// create new content, the last param is the userId and is optional [default = 0]
IContent newContent = contentService.CreateContent("My new document", parentID, "Textpage", 0);
// set property values
newContent.SetValue("propertyAlias", "Value");
// save (or save and publish)
contentService.Save(newContent);
}

ASP.Net MVC: how to create a JsonResult based on raw Json Data

Having a string containing the following raw Json data (simplified for the sake of the question):
var MyString = "{ 'val': 'apple' }";
How can I create a JsonResult object representing MyString?
I tried to use the Json(object) method. but it handles the raw json data as an string -logically :P-. So the returned HTTP response looks like:
"{ 'val': 'apple' }"
instead of the given raw Json Data:
{ 'val': 'apple' }
this is what I want to achieve:
The Json() method on Controller is actually a helper method that creates a new JsonResult. If we look at the source code for this class*, we can see that it's not really doing that much -- just setting the content type to application/json, serializing your data object using a JavaScriptSerializer, and writing it the resulting string.. You can duplicate this behavior (minus the serialization, since you've already done that) by returning a ContentResult from your controller instead.
public ActionResult JsonData(int id) {
var jsonStringFromSomewhere = "{ 'val': 'apple' }";
// Content() creates a ContentResult just as Json() creates a JsonResult
return Content(jsonStringFromSomewhere, "application/json");
}
* Starting in MVC2, JsonResult also throws an exception if the user is making an HTTP GET request (as opposed to say a POST). Allowing users to retrieve JSON using an HTTP GET has security implications which you should be aware of before you permit this in your own app.
The way I have generated json data from a string is by using JavaScriptResult in the controller:
public JavaScriptResult jsonList( string jsonString)
{
jsonString = "var jsonobject = new Array(" + jsonString + ");";
return JavaScript(jsonString)
}
Then when you request pass the json string to that action in your controller, the result will be a file with javascript headers.
I think you can use the JavaScriptSerializer class for this
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = js.Deserialize("{ 'val': 'apple' }", typeof(object));

Accessing resources via Uri in Asp.net mvc

I am working on an ASP.NET MVC web application in which I have an object with a Uri property. The Uri contains a restful link to a resource in the following form:
/Repository/Dataset/5
The Dataset action of the Repository controller returns the contents of dataset 5 as Json.
How do I call this method from the Uri and interpret the response as Json from within the object?
Many thanks.
In server side action return JsonResult.
public ActionResult Dataset(int id)
{
// reository code
return Json(model);
}
client side call $.getJSON.
My opinion is that you should not call your controller from anywhere in code.In ASP.NET MVC Controller is there to accept request, take data and choose proper view to be returned back.
Maybe you should add method on repository that is returning already JSONized data, or introduce "Middle man" that can serialize data returned from repository so controller can call middle man to do the job. Then repository (or "Middle man") can be called from anywhere in code.
e.g.(used Json.NET for json serialization):
public class MiddleMan
{
IRepository repository
public MiddleMan(IRepository repository)
{
this.repository = repository;
}
public string GetJsonObjects(int id)
{
return JsonConvert.SerializeObject(repository.GetObject(id));
}
}
then controller (or anywhere in the code) can call this middle class:
public string Dataset(int id)
{
return new MiddleMan(repository).GetJsonObjects(id);
}
For the time being I'm going to implement a uri extension method something along these lines, creating a WebRequest object for the Uri.
public static string GetContent(this Uri uri)
{
var myRequest = (HttpWebRequest) WebRequest.Create(uri);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
var sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();
return result;
}

Resources