This the server side Code
[System.Web.Services.WebMethod]
public static object GetDevelopers()
{
return new DqListViewModel(DQContext.Service._IDqs_IssueRepository.SelectList().ToArray(), 10);
}
View Model
public class DqListViewModel
{
public Array Data { get; set; }
public int Count { get; set; }
public DqListViewModel(Array data, int count)
{
this.Data = data;
this.Count = count;
}
}
This is the JSON return Value
why the JSON result has tow level object. I am not supposed to have "d" level?
Please check the below link. http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/
This is not an issue from Knedo-ui but it is the functionality of the Asp.net
Please try with the below link, may be it will help you.
How to bind JSON child array to Kendo grid
Related
I want to put an empty C# List to the razor view. Inside of the view I get array of data (taken from JavaScript code). Fill the content of the array into the C# List and put it back to the controller.
Now, I know that is not possible, then I find a more simpler solution, see details in my example.
One Item of the collection
public class GrafikSpielItem
{
public String Stil { get; set; }
public int XStart { get; set; }
public int YStart { get; set; }
public int XStop { get; set; }
public int YStop { get; set; }
public String Farbe { get; set; }
}
controller class
// GET: GrafikSpiel
[HttpGet]
public ActionResult AufgabeB(string[] arr)
{
// arr is the JSON-String from Grafik.js
if (arr == null) return View();
List<GrafikSpielItem> items = new List<GrafikSpielItem>();
// adapted from: https://stackoverflow.com/questions/19910476/c-sharp-parsing-json-array-of-objects
// Thanks to: Bibaswann Bandyopadhyay
JArray array = JArray.Parse(arr[0]);
foreach (JObject obj in array.Children<JObject>())
{
var item = new GrafikSpielItem();
int nCounter = 1;
foreach (JProperty singleProp in obj.Properties())
{
switch(nCounter)
{
case 1: item.Stil = singleProp.Value.ToString(); break;
// case 2: ..
default:
break;
}
nCounter++;
}
items.Add(item);
}
// not implemented yet
// connect to database
// db.SetData(items)
return RedirectToAction("Index");
}
Razor view
...
// moved source code from here to JS
<script src="~/Scripts/Grafik.js"></script>
</body>
</html>
JavaScript: Grafik.js
// convert simple array to JSON and send it back to controller
var arrStr = encodeURIComponent(JSON.stringify(linesArray));
var url = "AufgabeB?arr=" + arrStr;
window.location.href = url;
I found a solution - see edited code - thanks to user mortb and user Bibaswann Bandyopadhyay.
I'm quite new to Web-Api concepts. Trying to insert data using the basic project provided by Microsoft (Adding a simple Test Client to ASP.NET Web API Help Page).
http://blogs.msdn.com/b/yaohuang1/archive/2012/12/02/adding-a-simple-test-client-to-asp-net-web-api-help-page.aspx
Below is the code for Inserting data into Headoffice table.(HeadofficeID int ,HeadofficeName varchar(50),Notes varchar(1000),Isactive bit)
[POST("create")]
public HttpResponseMessage Post([FromUri]HeadOfficeModel headOffices)
{
if (_headOfficeBLL.Insert(headOffices) > 0)
return Request.CreateResponse(HttpStatusCode.Created, headOffices);
else
return Request.CreateResponse(HttpStatusCode.BadRequest, headOffices);
}
Headofficemodel Class
public partial class HeadOfficeModel : AtlAuthenticationModelBase
{
public int HeadOfficeId { get; set; }
public string HeadOfficeName { get; set; }
public string Notes { get; set; }
public bool IsActive { get; set; }
}
In the front end when i try to send the data from URI or Body only null values are getting inserting. While debugging all i can see in Headoffice model is null values.Below are the different ways i tried to insert data
1) {"HeadOfficeName":"TestHO1", "Notes":"notes", "IsActive":true}
2) {"TestHO1", "notes", true}
3) ={"headOffices":{"HeadOfficeName":"TestHO1","Notes":"notes","IsActive":false}}
and also tried to change the code as below
public HttpResponseMessage Post([FromUri]HeadOfficeModel headOffices)
public HttpResponseMessage Post([FromBody]HeadOfficeModel headOffices)
public HttpResponseMessage Post([ModelBinder]HeadOfficeModel headOffices)
Been trying to fix this from two days. When i send the data as complex type its not working else as separate parameters (changing the method to accept parameters) its working fine
public int Post(string Name, string Notes, bool Active)
{
HeadOfficeModel objHOM = new HeadOfficeModel();
objHOM.HeadofficeName = Name;
objHOM.Notes = Notes;
objHOM.IsActive = Active;
return _headOfficeBLL.Insert(objHOM);
}
Below is the html code where i m hiting while inserting
<script>
testClientModel = {
HttpMethod: '#Model.ApiDescription.HttpMethod',
UriPathTemplate: #Html.Raw(Json.Encode(Model.ApiDescription.RelativePath)),
UriParameters: [
#foreach (var parameter in Model.ApiDescription.ParameterDescriptions)
{
if (parameter.Source == System.Web.Http.Description.ApiParameterSource.FromUri)
{
#:{ name: "#parameter.Name", value: "" },
}
}
],
Samples: {
#Html.Raw(#String.Join(",", Model.SampleRequests.Select(s => String.Format("\"{0}\": \"{1}\"", s.Key, HttpUtility.UrlEncode(s.Value.ToString()))).ToArray()))
},
BaseAddress: '#applicationPath'
};
</script>
Can you please help me where am i going wrong. Attaching screenshot.
Entered both in URI and Body just to show that i tried different ways.
enter image description here
I need to restrict the values that I return to my page in a web method without using some sort of proxy object.
Let's say I have a Car class with the following class
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public string Engine { get; set; }
}
and a webmethod which looks like;
[WebMethod]
public static List<Car> SearchCars(string search)
{
var cars = car.All().Where(x => x.name.StartsWith(search));
return cars.ToList();
}
The list that get's return to my page has all attributes. How can I exclude say .. the engine attribute so only ID and Name are return?
The above is a purely fictional example, in the real world I'm using Subsonic3 objects to return a list etc.
You can use a projection to select only the fields you want returned. Something like this:
[WebMethod]
public static List<Car> SearchCars(string search)
{
var cars = car.All().Where(x => x.name.StartsWith(search)).Select(x => new { x.Id, x.Name });
return cars.ToList();
}
I'm not sure of the best way to approach this, but here is my scenario.
Let's say I have an ashx handler that feeds out some data to an ajax request from the client. Something simple like:
public class Handler : IHttpHandler
{
private List<MyObject> data;
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
data = GetData();
string result;
switch (context.Request.QueryString["requestType"])
{
case "case":
result = Foo.Bar(data).GetJSON();
break;
// .. several more data conversitions / comparisions
}
context.Response.Write(result);
}
public class MyObject
{
public int Id { get; set; }
public string Data { get; set; }
}
}
How would I cache the list of MyObject's so it is not rebuilt every time a request is made to the service? Let's say the list of MyObject gets thousands of results and I want to keep it cached for ~1 minute. Could I make use of context.Cache?
Basically; I do not want to cache the handlers output. Just an object with data that resides in it.
Edit:
I am looking for something along the lines of:
data = (List<MyObject>) context.Cache["data"];
if (data == null || !data.Any())
{
data = GetData();
context.Cache.Insert("data", data, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);
}
You can add result to HttpContext.Current.Cache, something like this :
var requestType = context.Request.QueryString["requestType"];
HttpContext.Current.Cache[requestType] = result;
How to return values from Webmethod to the client in JSON format?
There are two static int values that i want to return.
Do I need to create new object with those 2 properties and return it?
The GetStatus() method is called frequently and i don't like the idea of creating a special object each time just for json formatting...
[WebMethod]
public static int GetStatus()
{
int statusProcess,statusProcessTotal;
Status.Lock.EnterReadLock();
statusProcess=Status.Process; //Static field
statusProcessTotal=Status.ProcessTotal; //Static field
Status.Lock.ExitReadLock();
return ...
}
On client side I catch the return value in :
function OnSucceeded(result, userContext, methodName)
(PageMethods.GetStatus(OnSucceeded, OnFailed);)
I would just go with an object. It fits with what you need to do. If you have two return values you have to put them together in a structured way.
public class StatusResult
{
public int StatusProcess { get; set; }
public int StatusProcessTotal { get; set; }
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public StatusResult GetStatus()
{
int statusProcess,statusProcessTotal;
//Status.Lock.EnterReadLock();
statusProcess = 5;
statusProcessTotal = 1; //Static field
var result = new StatusResult();
result.StatusProcess = statusProcess;
result.StatusProcessTotal = statusProcessTotal;
return result;
}