简体   繁体   中英

How can I pass a URL parameter to a form field using MVC

I want to create a registration URL that will pre-populate the registration page with URL parameters in MVC. For example I have 3 text form inputs txtName, txtEmail, and txtCode. When the user clicks the registration link with his Name, Email, and Code embedded in the URL they will arrive at the registration page with these fields already populated so all they have to do is pick a password and click register.

  1. Can this be done using the URL and the View only or do I need to involve the Controler or Model?

  2. How would the URL look in this example www.somedomain.com/home/register

  3. What code needs to be implemented in the MVC if any?

A possible approach is to run JavaScript, on DOMContentLoaded , that'll take your query string params and pre-populate the applicable form fields. You can also do this on the server-side by accessing the Request.QueryString collection and populating the applicable input fields.

The MVC way to do this is to involve both the controller and the model.

  1. Create a view model class containing the fields of the registration form.
  2. Add the view model as the single parameter of the controller method.
  3. Send that view model directly to the view.

The URL will be of form http://example.com/home/register?Name=Anders

The controller will be really short:

public ActionResult register(RegisterViewModel model)
{
  return View(model);
}

The ViewModel should contain all properties that are present in the form:

public class RegisterViewModel
{
  public string Name { get; set; }
  public string Email { get; set; }
  public string Code { get; set; }
}

In the view, use the Html helpers to build up the form.

@model RegisterViewModel

// Html header, body tag etc goes here...

@using(Html.BeginForm())
{
  @Html.LabeFor(m => m.Name)  
  @Html.EditorFor(m => m.Name) 
  @Html.ValidationMessageFor(m => m.Name)
  // Rest of fields goes here
  <button>Submit</button>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM