hello
hello

Reputation: 1229

Remove ViewModel name from URL

I have a URL that looks like this

https://localhost/app/result?HomeViewModel.Prop1=Indiana+PA&HomeViewModel.Prop2=1

HomeViewModel is a Property of another ViewModel

Is there a way I can remove HomeViewModel from the URL, so it look likes this

https://localhost/app/result?Prop1=Indiana+PA&Prop2=1

Form that submits the parameters

@model CSharp.Models.ViewModels.ResultViewModel
@using (Html.BeginForm("Index", "Result", new { ViewBag.ReturnUrl }, FormMethod.Get, new { role = "form" }))
{
   @Html.TextBoxFor(model => model.HomeViewModel.Prop1)
   @Html.EnumDropDownListFor(model => model.HomeViewModel.Prop2)
   <button class="btn btn-primary" type="submit">Search</button>
}

Controller

public ActionResult Index(ResultViewModel model)
{
   var value1 = model.HomeViewModel.Prop1;
   var value2 = model.HomeViewModel.Prop2;

    var rvm = new ResultViewModel
    {
       otherProps = linq(value1),
       otherProps = linq(value2),
    };
  return View(rvm);
}

Upvotes: 0

Views: 897

Answers (2)

user3559349
user3559349

Reputation:

The code in your view is generating inputs that have name="HomeViewModel.Prop1" and name="HomeViewModel.Prop2" and a form posts back the name/value pairs of its form controls. If you want the the query string to be generated with .../result?Prop1=Indiana+PA&Prop2=1, then modify your view model to contain properties with those names

public class ResultViewModel
{
    public string Prop1 { get; set; }
    public yourEnumType Prop2 { get; set; }
    ....
}

and in the view

@Html.TextBoxFor(m => m.Prop1)
@Html.EnumDropDownListFor(m => m.Prop2)

and modify the POST method to

public ActionResult Index(ResultViewModel model)
{
   var value1 = model.Prop1;
   var value2 = model.Prop2;
   ....

Upvotes: 2

devio
devio

Reputation: 37225

First declare local variables

@{
    var Prop1 = Model.HomeViewModel.Prop1;
    var Prop2 = Model.HomeViewModel.Prop2;
}

then reference local variables instead of Model

@Html.TextBoxFor(model => Prop1)
@Html.EnumDropDownListFor(model => Prop2)

Upvotes: 1

Related Questions