Only Bolivian Here
Only Bolivian Here

Reputation: 36733

Simple way to get parameter from URL and place it into an input control?

I'm making an invite system where a user when registering to the site can specify a user who refereed them.

There's also a way for existing users to send invites. The friend would recieve a link:

http://www.foo.com/account/register?referal=sandyUser216

How can I get that value sandyUser216 and place it as the value inside of a text input box?

I'm using C# and MVC3.

Upvotes: 0

Views: 2157

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

As always in an ASP.NET MVC application you start by writing a view model that will represent the information contained in your view:

public class RegisterViewModel
{
    [Required]
    public string Referal { get; set; }
}

then you write controller actions for respectively showing the registration form and processing it:

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

[HttpPost]
[ActionName("Register")]
public ActionResult ProcessRegistration(RegisterViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    // TODO: perform the registration
    return RedirectToAction("success");
}

and finally you write the corresponding strongly typed view:

@model RegisterViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Referal)
    @Html.EditorFor(x => x.Referal)
    @Html.ValidationMessageFor(x => x.Referal)
    <button type="submit">Register</button>
}

Now all that's left is to simply navigate to /account/register?referal=sandyUser216.

And you have accomplished the whole MVC pattern. Should you skip any of those 3 letters it means that you are doing ASP.NET MVC incorrectly.

Upvotes: 1

Brandon
Brandon

Reputation: 69953

Check the Request.QueryString.

<input type="text" value="@Request.QueryString["referal"]" />

Or put it in a Model property rather than having it in the view.

Upvotes: 1

Related Questions