Sparkle
Sparkle

Reputation: 2469

Return a view with populated fields?

I am passing a query string to my account controller from a external source and I would like to add these values to the model and return the view. The below code is working but it is returning the view with the all the validation errors for the missing fields. I would simply like it to return the view with these fields populated?

One other issue is that I would like to return a clean url like /Account/Register without the Query String on the end of the address?

// **************************************
// URL: /Account/WriteRegistration/?Number=251911083837045755&Name=All&Remote=False
// **************************************

    public ActionResult WriteRegistration(RegisterModel model, string Number, string Name, bool Remote)
    {
        model.Number = Number;

        return View("Register", model);
    }

Upvotes: 0

Views: 328

Answers (3)

cyrotello
cyrotello

Reputation: 747

I think you may be approaching this badly.

If you're using a query string to populate your view, do this instead:

public ActionResult WriteRegistration(string Number, string Name, bool Remote)
{
    // Instantiate a new model here, then populate it with the incoming values...
    RegisterModel model = new RegisterModel() { Number = Number, Name = Name, Remote = Remote };
    return View("Register", model);
}

If you're looking for a clean URL, you may want to consider using a POST instead... that is, creating a form and submitting via a submit button. In that case you would do this:

[HttpPost]
public ActionResult WriteRegistration(RegisterModel model)
{
    // Model binding takes care of this for you, no need to set it up yourself.
    // ...but I'm guessing you'd do some logic here first.
    return View("Register", model);
}

I think your original code was mixing both approaches.

Upvotes: 2

ridecar2
ridecar2

Reputation: 1957

To return the clean Url you need to map the route, in your Global.asax add the following at the top of RegisterRoutes:

routes.MapRoute(
    "WriteRegistration",
    "Account/WriteRegistration/{Number}/{Name}/{Remote}",
    new {controller="Account", action="WriteResistration"},
    new {productId = @"\d+" }
);

Then /Account/WriteRegistration/251911083837045755/All/False will match.

To get the values into the view, pass them via the viewdata and set the form fields' default values to the values in the viewdata.

Upvotes: 1

Malevolence
Malevolence

Reputation: 1857

I believe you can call ModelState.Clear() to clear any errors generated by ModelBinding. That should get rid of the validation errors when you first load that page.

Upvotes: -1

Related Questions