开发者

MVC routing with parameters

开发者 https://www.devze.com 2023-04-03 18:11 出处:网络
I have a MVC3 app. For a URI like http://app/survey/Test i have the following survey/{name} which works great.

I have a MVC3 app. For a URI like http://app/survey/Test i have the following survey/{name} which works great.

This survey controller loads a bunch of questions

Each question has a bunch of possible answers

The possible answers are put in to a DropdownListBox or some other List friendly control

Now if a user hit a URI like http://app/survey/Test?city=London I want to somehow figure out in my Model.Question[i].PossibleAnswers collection that London is meant to be the default value for the Question "City".

If the user hit a URI like http://app/survey/Test?gender=Male&city=London&something开发者_如何转开发=SomethingElse

Then i want the Test survey to display

And it's gender question defaulted to Male

It's city question defaulted to London

It's something question defaulted to SomethingElse

Make any sense?

Anybody have any idea how to set this up?

It's a bit vague, so sorry about that but the best way I can think of describing this.

Thanks


You can use model binding as below and then pass

SurveyModel

to your controllor action in action method your can use SurveyModel. id for City SurveyModel.id2 ,etc

  public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            IValueProvider valueProvider = bindingContext.ValueProvider;

            string id = valueProvider.GetValueOrNullString("id");
            string id2 = valueProvider.GetValueOrNullString("id2");
            string id3 = valueProvider.GetValueOrNullString("id3");
            string id4 = valueProvider.GetValueOrNullString("id4");

            return new SurveyModel {Id = id, Id2 = id2, Id3 = id3, Id4 = id4};
        }

Refer Google Links for More details


You do not need to do anything, other than to specify your model in your HttpGet action, like so:

[HttpGet]
public ActionResult Test(Survey survey)
{ }

If you specify a model in the GET action, the querystring values will be passed into the model, since they are consumed by the QueryStringValueProvider, which makes them available to be bound to your model without any further action on your part.

0

精彩评论

暂无评论...
验证码 换一张
取 消