Silverlight, Grids, MVC, HTTP Post - asp.net-mvc

I'm trying to create an editable grid using Asp.Net MVC 2 and Silverlight (specifically a grid that displays info from a db and allows users to update that info).
So far I've managed to put a silverlight grid on an a view, using this technique
However I have no way of getting the updated data from the silver light grid. Is there anyway to get these values posted back to my controller?
I'm pretty new to Asp.Net MVC and I'm really only getting started using silverlight.
Thanks for any help!

The first thing you need to do is serialize back to JSON:-
(Assumption you use ToArray() on a ObservableCollection of MyItem objects)
public string SerialiseToJSON(MyItem[] myItems)
{
//Create a stream to serialize the object to.
MemoryStream ms = new MemoryStream();
// Serializer the User object to the stream.
DataContractJsonSerializer ser = new DataContractJsonSerializer(MyItem[]);
ser.WriteObject(ms, myItemsArray);
byte[] json = ms.ToArray();
ms.Close();
return Encoding.UTF8.GetString(json, 0, json.Length);
}
Now you can use the WebClient class to send the JSON string back.
WebClient web = new WebClient();
web.UploadStringAsync(new Uri("/yourcontroller/jsonReceiver", UriKind.Relative));
Now I don't know MVC all that well but I believe you can annotate a controller action method so that it can accept a http POST of JSON data and it'll do the deserialisation for you.

Related

Alternative to using Webclient to get HTML output

A product I've inherited is using WebClient to read HTML from a MVC based site. Each page is a different type of e-mail, so in order to compose and send an e-mail they use WebClient to request a URL and download the string.
var outputHtml = string.Empty;
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
outputHtml = client.DownloadString(emailURL);
}
return outputHtml;
Is there a way to remove the need to host this email based site but retain most of this code. I guess what I need to do is pass my request to the controller and retrieve the output after the razor engine has passed the view model through the cshtml page.
Is that possible?
There are many ways you could render a Razor view to a string. One possibility is to use RazorEngine. Another possibility is to use some specifically designed framework for this purpose such as Postal.

Get the body of a POST request in an MVC Controller Action

I have a WebJob that is posting a JSON object to a controller in my MVC website.
The default ModelBinder is not working correctly in this instance. Rather than troubleshoot the binder, I am perfectly happy to handle the serialization myself.
How do I get the body of the POST request from my controller Action so that I can feed it into JSON.net?
I have tried using a StreamReader on Request.InputStream, but I get an empty string.
I'm using Angular.js $http.Post() to send a json object to my actionresult, and the Model Binding was failing. I used the below code and was able to get the json object posted and then use Newtonsoft for the DeSerialization. Interesting thing is that Newtonsoft didn't throw an error on Deserialization while the default model binding in MVC did.
var req = Request.InputStream;
var json = new StreamReader(req).ReadToEnd();
var result = JsonConvert.DeserializeObject<Model>(json);

What's the best way to call a REST API from MVC4

MVC4 provides a very simple way to return serialized objects from HTTP requests. What's the best way to call a REST or other JSON/XML API from an MVC4 application? I could construct an HTTP request, send it, then deserialize the result, but I was hoping for something simpler. My application runs on multiple servers and one server needs to talk to the other via the web API. So, both servers have the same class definitions. I'm hoping there is some fairly transparent way to get MVC to deserialize as cleanly as it serializes content.
This is an example of how I call an MVC4 WebAPI from a WPF application. You should be able to adjust according to your needs. Hope this helps...
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://192.200.1.3:9594/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("EmployeeTest/TestApi");
if (response.IsSuccessStatusCode) {
var employee = response.Content.ReadAsAsync<Employee>().Result;
tbName.Text = employee.Name;
tbPhone.Text = employee.Phone;
}

How to extract values from Json String

I am developing an application using ASP.NET MVC 4 and it involves web API call where the result I am getting for a specific record is a Json string. I am doing this web API call inside an action method of a controller and the result I am getting for such call is in the following form:
result = "{\"fname\":\"John\",\"lname\":\"Doe\",\"empno\":123456,\"dept\":\"IT\"}"
I am new to MVC and Json and would really appreciate any help on how I can extract specific values from this Json string such as the value for dept?
Thanks.
In order to use this as an actual object in your project you will need to deserialize this string. .NET has it's own deserialization or you can check out Json.Net which is pretty simple to figure out. Check out the documentation on JsonConvert.DeserializeObject<>...
ie...
Instructor desInst = new Instructor();
responseContent = rsp.Content.ReadAsStringAsync().Result;
desInst = JsonConvert.DeserializeObject<Instructor>(responseContent);

Rich web app using ASP.NET MVC and Backbone.js and progressive enhancement

I'm working on a small web app using mvc and backbone.js and I have a couple of thoughts about how to handle async request vs regular requests.
Today I use a controller called /pages which returns a partial view if it's a ajax request and a standard view if it's a regular request. In another question I was told I'm doing it all wrong when I send a bunch of HTML back to the client.
So how should I structure my controllers etc to handle both async and non async requests?
In my case I have the following code in my pages controller
public ActionResult Index() {
var id = _model.Id;
var parentId = _model.Parent != null ? _model.Parent.Id : null;
var viewModel = new IndexViewModel
{
RootModel = _session.Query<IPageModel>().SingleOrDefault(model => model.Parent == null),
CurrentModel = _model,
ParentModel = parentId != null ? _session.Load<IPageModel>(parentId) : null,
Children = _session.Query<IPageModel>()
.Where(model => model.Parent.Id == id)
.Where(model => !model.Metadata.IsDeleted)
.OrderBy(model => model.Metadata.SortOrder)
.ToList()
};
if(Request.IsAjaxRequest()) {
return PartialView(viewModel);
}
return View(viewModel);
}
But if I understand things correctly I would be better off sending back a collection of pages instead of a complete view model? How should I handle this in my controller?
Is it a good idea to create a separate controller/api using eg. the api controller in mvc 4?
If you are using Backbone then you should return JSON insted of the PartialView and the PartialView should be a template in the page where the Backbone view will render that.
As mentioned earlier in different answers you should return JSON result instead of HTML view.JSON Result on MSDN Example of using JSON result
If you are using ASP.NET MVC 4 (as of now beta) you can use web api to get data in JSON through ajax/rest call.
I agree with Florim. You should be returning json from your MVC controllers. Backbone was built with REST in mind. Therefore your server should mimic a REST API, and return json for Backbone to work with. When I work with MVC 3 and Backbone, all my server code does is return the data. It usually has one view and that is the Backbone Application View. The web app "views" are rendered using templates from the data that is returned from my controllers. Hope this helps.
I have not played with the MVC 4 Web API as of yet, but I do think this situation would be the ideal choice for it.
I've compiled a couple of Backbone examples together into a working ASP.net MVC 3 application that is using REST interface. Here is the link to my tumblr Blog where I have provided information to the source code and the websites I used as resources. Backbone.js works really well with MVC 3 and I am always looking for new ways to push this example.

Resources