MVC 4 WebAPI - Is there a way to get a dictionary of values passed to a POST action? - asp.net-web-api

I am able to successfully retrieve an object via POST action.
I am trying to build a proof of concept for dynamic treatment of form values posted, so that I do not know at design time what those names or values will be.
Is there a particular type of binder or formatter etc. that should be added after [FromBody] attribute in the post action to achieve this?
Essentially I need a name-value-pair. I tried KeyValuePair and dynamic. Dynamic returns an object. I don't know how to get the key names and values out of it.

This should do what you are looking for.
public HttpResponseMessage Post(FormDataCollection collection) {
...
}

Related

Spring passing object/string between controllers (GET & POST)

I've been struggling with passing some value between controller.
I have one controller like this:
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String addGet(HttpServletRequest request, #ModelAttribute(value="branch") Branch branch, Model model, blahblahblah)
//What I want to pass and re use:
String loadRespond;
try{
loadRespond= *SOME LOAD STRING METHOD*;
branch= branchManager.convertString(loadRespond); //METHOD TO SPLIT STRING & INDUCT TO OBJECT
}catch{exception){
//blabla
}
After I successfully inducted all the attributes into the object branch,i show them all through a binding form. What i want to do is, when i'm going to update the data/change some attribute, i want to compare the old branch to the new changed branch. This means that i have to pass the old branch object or the loadRespond string onto the POST method so that can be used. Do anyone have any idea of how to do this? Maybe to assign it to hidden type field in the jsp? and then use it on the controller with request mapping /add of method type post? Thanks..I'm a newbie..
Why don't you try out with session scope ?
store your old branch into the session . and when you get the new object compare with the old one (by retrieving from session)
You can save into session as any of both,
request.getSession().setAttribute("sessionvar", "session value");
#SessionAttributes("sessionvar")
A nice Example here to start with it.
Side-note : your question title doesnt quite expalain your problem and the solutions may vary
As San Krish notes in his answer the most common way is to use #SessionAttributes and pass objects/data using them.
This is useful if you don't worry about user moving backwards and forwards in a page, or want basic control of the object.
Now if you want to have a chain where controller 1 passes to controller 2 which may pass to controller 3 your best bet is to implement web flows.
Summary:
For short and sweet and quick: SessionAttributes is the way to go, example here http://www.intertech.com/Blog/understanding-spring-mvc-model-and-session-attributes/
For chain passing, greater control and validation use Spring Web Flows.

input validation not working on asp.net mvc 4 model sent as JSON

I have a model and a form in the view. I have a simple field of string which is called description. I'm able to insert scripts like: <script>alert('xss')</script> to that field.
I can see that in other actions on my site with other models I can't
I do not have an AllowHtml or anything like that.
the only difference is that for this model I use a post with a json object and content-type of application/json
the ModelState.IsValid is returning true. even though there is a description property with an xss script on it...
and for the other actions I make a simple ajax post.
why isn't the validation input work on this kind of JSON ajax posts?
how can I prevent xss across the entire site for this kind of ajax requests?
thanks
It is because ValidateInput is only for FormValueProvider. As for JsonValueProvider, you need to roll out your own mechanism.
Steps
1) Create a marker attribute CustomAntiXssAttribute
2) Create a custom model binder by sub-classing DefaultModelBinder
3) Overrides BindProperty method -> get the attempted value for the underlying property, sanitize it and assign it to the view model property.
Check this out.
Edited:
Replace the line var valueResult = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name); with var valueResult = bindingContext.ValueProvider.GetValue((string.IsNullOrWhiteSpace(bindingContext.ModelName) ? string.Empty : bindingContext.ModelName + ".") + propertyDescriptor.Name); in order to support nested ViewModel.
try using AntiXssLibrary from Nuget, and by using getSafeHtmlContent. you can get the safe content while you're saving your records to db.
Another approach is to use a Sanitizer library like this one, you can choose which HTML tags you want to be filtered out.

Kendo UI Datasource and Arrays

I am sending over a series of array values from a posted form to an MVC3 Controller. I was hoping the default modelbinder would be able to parse this but I'm having some difficulty with it.
The array is in the following format:
order[0].[type]=some value.
I think this is the reason the model binder is not parsing my values because I'm not getting anything populated in my model.
What would be another way to handle this?
Probably need to post more of your code so I can see what you are doing exactly. However saying this you need to pass the model to the view/partial view on the response you are trying to retrieve on the post request.
If not you will have to iterate through the Form Collection that will be returned and the Actions Methods type e.g. ActionMethodName(FormCollection form), one issue is name versus id its the name of the Kendo UI control that is used to get the value not the id.
1As far as I remember the right format was:
orders[0].OrderID=13;
orders[0].Name="test";
orders[1].OrderID=15;
orders[1].Name="again test";
The indexing should start from 0 and increase by 1.
Check this out: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

ASP.NET Web API - GET request with multiple arguments

What I'm trying to do is to have an api request like /api/calculator?1=7.00&2=9.99&3=5.50&4=45.76 etc. How my controller can grab the request data? The keys/codes of the query string are ints between 1 and 1000. In the query string they can be some of the 1000 codes, not necessarily all of them. The value part is doubles.
The one way I think would work is if I create a model object (ex StupidObject) with 1000 properties (should use properties named like p1, p2,..p1000 for codes now, as ints are not an allowed property name), decorated with ModelBinder. Then for the controller I could have something like GetCalcResult(StupidObject obj){...} But that doesn't seem like an elegant solution :)
I tried controllers like GetCalcResult([FromURI]Dictionary<int, double> dict){...} but dict is always null. Also without the [FromURI] I get an error. Also tried List<KeyValuePair<int, double>> as controller parameter with the same results.
Could anyone point me at the right direction or give me an working example?
One way is to avoid trying to pass the values in as a parameter and simply do
var queryValues = Request.RequestUri.ParseQueryString();
in your action method. QueryValues will be NameValueCollection that you can iterate over to get access to your query parameters.
If you really want to use a parameter, having a parameter of type [FromUri]FormDataCollection might work.

MVC3, turn off field validation for a field not in a ViewModel

I have a Form in an MVC3 project. One of my input fields should accept HTML. Unfortunately I cannot have a ViewModel which this value maps to. The Field is autogenerated and read in automatically. I am getting the following error.
A potentially dangerous Request.Form value was detected from the client
Since there is no viewmodel, I cannot apply the [AllowHTML] attribute. Does anyone know a workaround that does not involve disabling validation for the entire page?
Thank You
Additional Information:
I can access the unvalidated value by doing the following:
using System.Web.WebPages;
using System.Web.Helpers;
.....Inside Controller....
string value = Request.Unvalidated("input-40");
The problem now is that the Request.Params collection throws an exception. I would like to access all the other values and have them be validated...just not that one. Is there a way for me to validate the other fields either explicitly or access a validated collection.
The following would be fine
string value = System.Web.Something.ValidateInput(Request.Unvalidated("input-41"));
Unfortunately I don't know where/if this method exists
You can try the ValidateInput(false) attribute:
[ValidateInput(false)]
public ActionResult YourAction(FormCollection yourCollection)
{
// your stuff
}
Use ValidateInput attribute for your action method. Seems to be unsafe but should work, cannot test it now.

Resources