Asp.net Core 2 Read Url Parameter in View Page
All I want to exercise is brand a unproblematic page that allows users to update a database by filling in a course!
You lot take a form, you take an ASP.Cyberspace Core MVC awarding, but how on earth are y'all supposed to go the data from the form to your ASP.NET Controller actions?
Table of Contents
- Wire upward the form manually
- Employ Tag Helpers
Turns out you have two options (well, really there are more than that, but let'southward focus on these 2 for starters).
#ane The manual way (using plain one-time HTML forms)
Let's say you need a way to tape someone'due south basic details (similar their proper noun, age etc).
To accomplish this y'all're going to need a grade, which can be wired upwards to submit whatever information the user types in, back to your application.
Your app can then exercise whatever it needs to with that information (shop information technology in a database, electronic mail it to someone etc.).
Let's start with the fleck our users will actually see; the class itself.
<form method = "Postal service"> <label for = "firstName">Your start proper name</label> <input type = "text" id = "firstName" placeholder = "Your name goes here" /> <input type = "submit" /> </course>
On offset glance, our HTML form looks reasonable. We've got a single text box (firstName) and the course is going to send its data via an HTTP Mail service.
Unless we indicate otherwise, this will post back to the same location used to serve the form.
So, using default routing conventions, we could use a controller like this…
public class FormController : Controller { [HttpGet] public IActionResult Index() { return View(); } [HttpPost] public IActionResult Index(cord firstName) { return Content($"Hello {firstName}"); } }
Nosotros'll see our class if nosotros browser to http://<YourSiteHere>/course
.
When nosotros submit the form, it will exist posted to the same address (http://<YourSiteHere>/grade
) (as an HTTP Mail request).
But, we have a fatal flaw in our course! Run this, enter a name, submit the form and all you'll get is a half-complete judgement.
For the value of the input to exist submitted as course information, it needs to take a name attribute.
<input type = "text" id = "firstName" placeholder = "Your name goes here" proper name = "firstName" />
With the proper name aspect in place, ASP.NET MVC spots the incoming "firstName" value (in the submitted form information) and binds it to the firstName
parameter we specified in the Alphabetize
(POST) method on our controller.
Diagnose form data bug
When you come across bug like this, information technology isn't always obvious what's causing the trouble.
This is where the Chrome network tab comes into its own.
Submit your form with the programmer tools open (F12) and you lot'll see the class post in the network tab.
Click the relevant request and cheque out the Grade Data section.
In this example you tin see that firstName
has been submitted as form data and so should be bachelor to ASP.Internet Core.
If you lot don't see the values y'all expect then the chances are your form isn't working properly and that'south where to focus your efforts on fixing the trouble.
#ii Using Tag Helpers
Now we know how to manually set up our forms to post the right data, correctly tagged so our MVC controllers know how to handle it.
Merely this seems like a bit of a faff (and is asking for trouble every time we rename anything either in the HTML or the C#).
With ASP.NET Cadre you have an alternative.
You lot can use Tag Helpers to save you manually adding name attributes to all of your input fields.
Starting time upward, create a course to act as the model for our page.
public course FormModel { public cord FirstName { become; set up; } }
Now we tin tweak our view (cshtml page) to apply this model by calculation a model declaration at the elevation.
@model FormBasics.Controllers.FormModel
When you endeavour this for yourself, brand sure yous specify the correct namespace, where your model exists.
With that in identify, nosotros tin offset using tag helpers to exercise some of the plumbing (e.yard. calculation name attributes) nosotros'd otherwise have to do ourselves.
<form asp-action = "Index" asp-controller = "Course"> <label asp-for = "FirstName"></label> <input asp-for = "FirstName" placeholder = "Your proper name goes here"/> <input type = "submit" /> </course>
We've made a few changes here.
First we've explicitly defined the activeness and controller that this course volition post back to, using asp-action
and asp-controller
. This isn't strictly necessary, simply it doesn't hurt to be explicit, but in example we kickoff moving things around, the form will continue to post to the correct controller action.
Secondly, because this folio now knows virtually its model, we tin apply the asp-for
tag helper on our input
and label
elements, specifying the relevant property name from our model.
Here's the resulting grade.
And here's how this will exist rendered (it's oft worth taking a look at the source code in your browser to meet what HTML we end upwards with in cases like this).
<class action = "/Form" method = "postal service"> <label for = "FirstName">First Proper name</label> <input placeholder = "Your proper name goes here" type = "text" id = "FirstName" proper name = "FirstName" value = ""> <input type = "submit"> <input name = "__RequestVerificationToken" type = "hidden" value = "<token_generated_here>"> </form>
Note how ASP.NET has picked up that the rendered class should make a POST
to /form
and has automatically included the proper name
attribute for the input field.
If you're wondering what the __RequestVerificationToken
is, this is a neat fashion to reduce the take chances of your application being duped by a cross site request forgery attack.
I've got a model and I'thou non afraid to utilize information technology
Now we've got a model we can become rid of that string parameter in the Index POST action and supervene upon it with a FormModel
parameter.
[HttpPost, ValidateAntiForgeryToken] public IActionResult Alphabetize(FormModel model) { render Content($"Hello {model.FirstName}"); }
ASP.Net MVC Core will bind the course data to your model automatically.
This also means we won't observe ourselves constantly updating the Index
action every fourth dimension nosotros need to handle another value submitted via the form.
Incidentally, I've also added the other one-half of the Request Verification Token check here (the ValidateAntiForgeryToken
attribute) to make sure this form has been posted from our site (and non a malicious site hosted by someeone else).
A amend label
Finally, by default the asp-for
tag helper on our label has used the proper name of the property for its value.
We can ameliorate this and exist explicit nigh what the characterization should say, with an attribute on our model.
public grade FormModel { [DisplayName("Beginning Proper noun")] public string FirstName { get; set; } }
Admittedly, this course isn't going to win whatever prizes for its design, but at least the label reads a little better!
What near HTML Helpers?
If you've used previous versions of MVC, yous're probably familiar with the HTML Helpers from previous versions. They look like this…
@Html.TextBox("firstname")
I huge benefit of Tag Helpers over HTML Helpers, is that they leave yous free to define your markup using standard HTML tags. Rather than accept some magic render the entire element for you, the tag helper extends your standard HTML element. This is evident in our example where we are gratuitous to add a placeholder aspect to the FirstName input without jumping through extra hoops to bend an HTML Helper to our will.
In Summary
Lean on ASP.NET Cadre'southward Tag Helpers to go your forms up and running.
Wire upwardly your inputs (text boxes etc) to something on the model (using Tag Helpers) and the value entered past the user will be submitted as formdata
when the user submits the grade.
ASP.NET Core'south model binding will then kick in and assign the posted values to an instance of the Model.
From here, you can do any you demand to with the model (including saving it to a database etc.)
Next upwardly
But, which flavor of ASP.NET?Blazor, Razor, MVC… what does it all hateful?!
At that place's a buzz about Blazor - Here's whyPeople are talking nearly Blazor simply will it ever really replace JS?
Starting out with the ASP.NET Core React template (part 3 - Separating out the frontend)How to run the frontend and backend parts of the ASP.Cyberspace Cadre React projection template separately
Source: https://jonhilton.net/2017/08/17/how-to-get-data-from-an-html-form-to-your-asp.net-mvc-core-controller/
0 Response to "Asp.net Core 2 Read Url Parameter in View Page"
Post a Comment