Silverlight and MVC: post object to controller method - asp.net-mvc

I have an MVC project in which a controller action returns some JSON data (i.e. via /Home/GetData URL). This action also takes a custom object as a param.
This signature for the action is JsonResult GetData (MyCustomObject o)
I also have a client Silverlight project in which I'm constructing MyCustomObject and trying to call this URL (/Home/GetData/) via HttpWebRequest. However, I'm having trouble figuring out how to post in my object in this call. Do I need to serialize it to Json in order to pass it in?
Thanks so much!

MVC can accept and bind the submitted data to your MyCustomObject object, regardless of whether it is submitted as JSON, XML, a query string, a standard form POST, etc.
MVC does not require the object to be submitted in a particular fashion. That is up to you as the designer to determine what works best under the particular circumstances, given all of your requirements.
When submitted, MVC will use the ValueProvider suitable to the form of the data submitted, and the DefaultModelBinder will attempt to use the values in the ValueProvider to bind to your model.

Thanks for your help! Since the web app handles this with a getJSON call, I ended posting the object as a query string param i.e. I'm making a web request to http://../controller/action/view.aspx?custObject.property1=<value>&custObject.property2=<value> etc

Related

How to access "main" querystring from ActionMethod called from Partial

In an MVC project, I have a partial
#Html.Partial("_MyPartial");
which calls a controller method (using AJAX with jQuery) via URL
'/Home/MyActionMethod?type=myType&sort=az&page=1'
The Home controller contains MyActionMethod, which returns a PartialViewResult.
MyActionMethod has parameters matching those in the URL, which are mapped as per usual.
My question is how to access the top level querystring from MyActionMethod, because I want to include extra values in there? By top level I mean the one seen in the browser, as opposed to the one sent to MyActionMethod from _MyPartial
Many thanks
You have to include them as query string parameters when performing your AJAX call. So when building the link on the server, read the query string parameters and append them to those that you have already.

Best way to add filter to URL in .NET MVC

I'll try to make this as concise as possible.
Webpage contains a table that allows for filtering and sorting
Changes to filtering and sorting should be reflected in the URL so the user can bookmark or share filtered views.
The question is: What is an effective convention of allowing all of the sort and filter syntax to be part of the URL and easily interpret/use it on the server without having to write a bunch of custom code that interprets it?
I've been doing some research and I came across the OData URI conventions and I like the way they do things.
http://www.odata.org/developers/protocols/uri-conventions
More research shows the the MVC 4 Web API allows for use of that convention by returning an IQueryable. This looks fantastic except for one part... I'm not implementing a RESTful API at this point and that's all it seems to work with. So how can I use something like OData and still return a View or PartialView? Is there something that will parse the OData URI convention into a C# object?
If anyone has any insights into this problem or suggestions, I'm all ears.
As for the url convention part of your question, I think you have answered your own question with OData. As for getting this data into a C# object I would use the following approach:
Use an action filter to interperet the url parameters and parse them into a c# object.
In your action filter add the url parameters to the route data and the c# object will be available in your action.
ASP.NET MVC Pass object from Custom Action Filter to Action
Take a look at the Telerik MVC grid, they use a GridAction action filter that does pretty much what you are asking.
I would look at custom model binding. A good overview can be found here: http://weblogs.asp.net/nmarun/archive/2010/02/25/asp-net-mvc-model-binding.aspx
It's typically used for POST requests with forms but there's no reason why you can't use it for GET requests too.
Basically, your approach should be to:
Create a new Model class with your filter/sorting parameters as properties:
public class TableParameters {
public string TableFilter { get; set; }
}
In your Controller's Action, add the model as a parameter
public ActionResult TableAction(TableParameters parameters) { /* Action logic */ }
Set your parameters in the URL by saying:
/Controller/TableAction?TableFilter=[your-filter-string]
The parameters object in your action will have the property populated with the value from the query string.

MVC why is UpdateModel sometimes used in Edit and sometimes not

I'm new to MVC and I've been looking through a bunch of examples.
For the HttpPost on some edits they call UpdateModel(entity).
In other examples such as:
http://www.asp.net/mvc/tutorials/mvc-music-store-part-5
UpdateModel(entity) isn't called at all.
What's the point of calling this function when it appear unneccessary in MVCMusicStore?
Apparently it " Updates the specified model instance using values from the controller's current value provider."
However I've found from the MVCMusicStore example the updated values are already posted through?
Could someone please explain this to me?
There should be no reason for you to use UpdateModel in the newer version of ASP.NET MVC
Originally it was provided because when you posted your data back to the action on your controller, a FormsCollection would be passed in to to the action and then a call to UpdateModel(entity) would be required.
However in newer versions of ASP.NET MVC the concept of ModelBinding has been introduced which will allow your actions to define a .net object to be passed in to your action methods and the model binder will take care of "binding" the values to the model.
To be completely honest, I'm not sure why they don't just deprecate the UpdateModel() method because AFAIK it's completely redundant.
Use UpdateModel for PATCH semantics. From RFC5789:
The PATCH method requests that a set of changes described in the
request entity be applied to the resource identified by the
Request-URI.
This means you are making modifications to an existing resource (e.g. from the database).
Use the object as action method parameter for PUT semantics.
The difference between the PUT and PATCH requests is reflected in the
way the server processes the enclosed entity to modify the resource
identified by the Request-URI. In a PUT request, the enclosed entity
is considered to be a modified version of the resource stored on the
origin server, and the client is requesting that the stored version be
replaced.
In practice, there's not much difference if the request contains values for all of the resource members. But if the request only contains values for a subset of the resource members, in PATCH the other members are left unmodified, and in PUT are set to their default value (usually NULL).
i don't think ModelBinding is only introduced in newest version of asp.net mvc (newest version is 3). it was present at least in v-2 so far as i can tell. when you call the updatemodel you call Modelbinding explicitly. when you receive at as action method parameter Modelbinder is called implicitly.
In Edit scenario updateModel is used when we fetch original entity from db and tell controller to update it using UpdateModel like
public ActionResult Edit(int id)
{
var entity = db.GetEntity(id);
UpdateModel(entity);
db.SaveChanges();
}
Other scenario is when you are not fetching db entity but ModelBinder gives you an entity created from form fields etc. and you tell you db that object is already there and it has been modified outside the db and you better sync with it like in MusicStore tutorial.

What is "posted" in ASP.NET MVC applications?

As I review more code and blog posts from lots of MVC sources, I still haven't wrapped my mind around what is "posted" when a request is made. I realize MVC doesn't support post, but I'm having trouble finding resources that can explain it well enough to understand.
Inside the controller's public ActionResult nameOfAction(what the heck goes here?) { ... } what are my parameters?
Sometimes it looks like Visual Studio scaffolds (int id, MyObject myobject) for an Edit-style action--it includes something from my model, but not always.
Sometimes, it's (int id, FormCollection collection) for a delete-style action. Why not use the modeled object here? Is a FormCollection object always "posted"?
Sometimes, I see (RouteInfo routeInfo) which isn't recognized in my MVC2 Intellisense (is this MVC1 only or something?)
How can/do/should I establish these parameters? I think this will help me a lot at design time.
What gets post back from a form in MVC is the form data which includes each form element in a keyvalue pair.
If you only need this information then you would use:
public ActionResult nameOfAction(string name, string lastName, string etc)
MVC has some smart data model binding which takes the form data and automatically creates an object which is part of you domain model. For instance it could automatically create a Person object with the provided form data.
I believe there is a security concern with this as a user of your site may post data which is not part of your form and guess what your models are to inject their own data.
I dont think this is a massive issue though and this is the way I would go.
I think you can use the anti-forgery helper to prevent users from posting back data which is not allowed in a form. anti-forgery
Use strongly typed views with a view-model and the strongly typed helpers. Then when you POST, you should get an instance of that view-model out.

Request.Form not populated when using the HTTP PUT method (ASP.NET MVC)

I'm attempting to process the body of an HTTP PUT request, but it seems that the MVC engine (or perhaps the ASP.NET stack underpinning it) isn't automatically parsing & populating the request's Form collection with the body data.
This does work as expected when doing a POST.
Note that the request's InputStream property does contain the expected data, and obviously I can build my own key/value collection using that, however I would have expected PUT to work the same way as a POST.
Am I missing something here?
Example action method:
[AcceptVerbs(HttpVerbs.Put)]
public ActionResult Purchase(int id, FormCollection data)
{
// Do stuff with data, except the collection is empty (as is Request.Form)
}
Quote from the doc:
The Form collection retrieves the
values of form elements posted to the
HTTP request body, with a form using
the POST method.
So instead of using Request.Form I would recommend you writing a custom model class that will hold the request data and pass it as action parameter. The default model binder will automatically populate the properties from the key/values passed in the request stream:
[AcceptVerbs(HttpVerbs.Put)]
public ActionResult Purchase(MyCustomModel model)
{
// Do stuff with the model
}
Asp.net does not support PUT out of the box for custom requests. If you are using not the built in capabilities to generate the PUT url try adding X-HTTP-Method-Override with value of PUT in headers, form, or query string.

Resources