QueryString is always empty ASP.net Core 3.1 - model-binding

The query string I use is always empty. I have no idea why, and have tried for hours with
The HttpContext.Request returns all other parts of the URL except the querystring.
With this url https://localhost:44394/Trackers/Create?Place=Vision_College
and this Model
[BindProperties(SupportsGet = true)]
public partial class Tracker
{
[FromQuery(Name = "Place")] //populates it from the query
public string Place { get; set; }
...}
and this controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Name, Phone, Place")] Tracker tracker)
{

OK I found an answer.
I was trying to use it in the POST of the CREATE, when I should have been using it in the GET part of CREATE
Thanks for everyones help!

Since you are using the query parameters in httpPost you should use, [FromQuery] inside your arguments. Follow this
Your DTO class would be,
public class Tracker
{
[FromQuery(Name = "Place")]
public string Place{ get; set; }
}
In your controller class
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([FromQuery]Tracker tracker)
{
}
Note: If your query parameters match with the model property names, specifically annotating the properties would not be necessary.
Better you can get by body itself since this is a post request. otherwise make this as a get request. If converting to get by body, simply use [FromBody] in endpoint arguments instead of [FromQquery]

Related

Invoke POST method using Breeze not working

I am working on single page application using HotTowel. I have referred below link for invoking POST method using breeze.
http://www.breezejs.com/breeze-labs/breezeajaxpostjs
Below is my code.
On Server side:
public struct Customer {
public string CompanyName{ get; set; }
public string Phone { get; set; }
}
[HttpPost]
public IQueryable<Customer> SimilarCustomersPOST(Customer customer)
{
return repository.CustomersLikeThis(customer);
}
Invoking POST method using breeze.
var query = breeze.EntityQuery.from('SimilarCustomersPOST')
.withParameters({
$method: 'POST',
$encoding: 'JSON',
$data: { CompanyName: 'Hilo' , Phone: '808-234-5678' }
});
I am getting below error:
Error: The requested resource does not support http method 'GET'.
When I am writing a server code like below:
[System.Web.Http.AcceptVerbs("GET", "POST")]
[HttpPost]
public IQueryable<Customer> SimilarCustomersPOST(Customer customer)
{
return repository.CustomersLikeThis(customer);
}
It is invoking but accepted parameters getting null values.
Please let me know what is the reason I am getting this error.
Thanks in advance.
I'm not sure what happens when you mix [HttpPost] with [AcceptVerbs("GET")], but that might be the problem.
Note that in a GET method you need to use the [FromUri] attribute in front of parameters that are not simple value types, but you don't need that in a POST method. This blog post explains WebAPI parameter binding nicely.

URL Parsing - routing or other?

I am in the process of migrating PHP code to ASP.NET MVC and previously for the register page I would store if the new user had accepted the rules and also was COPPA verified by redirecting from /register to /register&readrules=1&coppa=1. I would then just parse the #readrules and #coppa in the code.
What is the best way to do this in ASP.NET? Thanks
Use query string parameters instead:
/register?readrules=1&coppa=1
This is more standard and you do not need any parsing. Just define a view model to accomodate those values:
public class MyViewModel
{
public int Readrules { get; set; }
public int Coppa { get; set; }
}
and ten have your Register controller action take this view model as parameter:
public ActionResult Register(MyViewModel model)
{
... at this stage model.Readrules and model.Coppa will contain the values passed
as query string parameters tat you could use here
}
The default model binder will automatically bind the values of the readrules and coppa query string parameters to the corresponding properties of the view model that your controller action takes.

asp.net mvc form values display

I'm new to asp.net mvc. Basically i'm from php programmer. In my php file i can display what are all the values coming from html page or form using echo $_POST; or print_r($_POST); or var_dump($_POST). But in asp.net how can i achieve this to check what are all the values are coming from UI Page to controller.
You may take a look at the Request.Form property:
public ActionResult SomeAction()
{
var values = Request.Form;
...
}
You could put a breakpoint and analyze the values. Or simply use a javascript development toolbar in your browser (such as FireBug or Chrome Developer Toolbar) to see exactly what gets sent to the server.
But normally you are not supposed to directly access the raw values. In ASP.NET MVC there's a model binder which could instantiate some model based on the values sent to the server.
For example you could have the following model:
public class MyViewModel
{
public int Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
and then have your controller action take this model as parameter:
public ActionResult SomeAction(MyViewModel model)
{
... you could use the model properties here
}
and now you could invoke this controller action either wityh a GET request passing the parameters in the query string (/someaction?age=10&firstname=foo&lastname=bar) or using a POST and sending them in the body.
You can check the raw data via Request.Form.
But this is not he spirit of the ASP.NET MVC. It is preferd that you expect a model into your controller. You have all type safety mapping already done by special module called model binder.
So unless you work on some special case, you just add a model to the controller action:
public ActionResult SomeAction(SomeModel model)
{
//Handle SomeModel data further ...
}
You can create an action which will accept the parameters from the UI page like the following:
[HttpPost]
public ActionResult SomeAction(string param1, int param2)
{
//Now you can access the values here
}
or make an action which will accept the model
public ActionResult SomeAction(SomeModel model)
{
//Access the model here
}

asp.net MVC 3 - reading POST payload in paramterized controller method

I had
[HttpPost]
public ActionResult Foo()
{
// read HTTP payload
var reqMemStream = new MemoryStream(HttpContext.Request.BinaryRead(HttpContext.Request.ContentLength));
....
}
The payload is application/json; worked fine; then I changed to
public ActionResult Foo(string thing)
{
....
}
The intention being to post to MyController/Foo?thing=yo
Now I cant read the payload(the length is correct but the stream is empty). My guess is that the controller plumbing has eaten the payload looking for form post data that can be mapped to the method parameters. Is there some way that I can stop this behavior (surely MVC should not have eaten a payload whose type is marked as JSON , it should only look at form post data). My work around is to add 'thing' to the json but I dont really like that
Try resetting the input stream position before reading:
public ActionResult Foo(string thing)
{
Request.InputStream.Position = 0;
var reqMemStream = new MemoryStream(HttpContext.Request.BinaryRead(HttpContext.Request.ContentLength));
....
}
Now this being said, if you are sending an application/json payload why on the holy Earth are you bothering to read directly the request stream instead of simply defining and using a view model:
public class MyViewModel
{
public string Thing { get; set; }
public string Foo { get; set; }
public string Bar { get; set; }
...
}
and then:
public ActionResult Foo(MyViewModel model)
{
// use the model here
....
}
ASP.NET MVC 3 has a built-in JsonValueProviderFactory which allows you to automatically bind JSON requests to models. And if you are using an older version it is trivially easy to add such factory your self as Phil Haack illustrates in his blog post.

Using named parameters as controller input versus FormCollection

I'm new to ASP.NET MVC so this could have an obvious answer. Right now I have a form in my view with a lot of input controls, so I have an action that looks like this:
public ActionResult MyAction(string formItemOne, int? formItemTwo, etc...)
It has like a dozen parameters, which is pretty ugly. I'm trying to change it to this:
public ActionResult MyAction(FormCollection formItems)
and then parse the items dynamically. But when I change to a FormCollection, the form items no longer "automagically" remember their values through postbacks. Why would changing to a FormCollection change this behavior? Anything simple I can do to get it working automagically again?
Thanks for the help,
~ Justin
Another solution is to use models instead of manipulating the raw values. Like this:
class MyModel
{
public string ItemOne { get; set; }
public int? ItemTwo { get; set; }
}
Then use this code:
public ActionResult MyAction(MyModel model)
{
// Do things with model.
return this.View(model);
}
In your view:
<%# Page Inherits="System.Web.Mvc.ViewPage<MyModel>" %>
<%= Html.TextBox("ItemOne", Model.ItemOne) %>
<%= Html.TextBox("ItemTwo", Model.ItemTwo) %>
To replace your big list of parameters with a single one, use a view model. If after the POST you return this model to your view, then your view will remember the values posted.
A view model is simply an class with your action parameters as public properties. For example, you could do something like this, replacing:
public ActionResult MyAction(string formItemOne, int? formItemTwo, etc...)
with
public ActionResult MyAction(FormItems formItems)
{
//your code...
return View(formItems);
}
where FormItems is
public class FormItems
{
public property string formItemOne {get; set;}
public property int? formItemTwo {get; set;}
}
You may see a complete example in Stephen Walter's post ASP.NET MVC Tip #50 – Create View Models.
Maybe because they aren't magically inserted into the ModelState dictionary anymore. Try inserting them there.
If you use UpdateModel() or TryUpdateModel() I think the values are gonna be persisted.

Resources