从URL中删除ViewModel名称

时间:2017-02-19 22:38:14

标签: c# asp.net asp.net-mvc

我有一个看起来像这样的网址

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

HomeViewModel是另一个ViewModel的属性

我是否可以从网址中删除HomeViewModel,因此它看起来像这样

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

提交参数的表单

@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>
}

控制器

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);
}

2 个答案:

答案 0 :(得分:2)

视图中的代码生成的输入包含name="HomeViewModel.Prop1"name="HomeViewModel.Prop2",并且表单会回发其表单控件的名称/值对。如果希望使用.../result?Prop1=Indiana+PA&Prop2=1生成查询字符串,则修改视图模型以包含具有这些名称的属性

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

并在视图中

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

并将POST方法修改为

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

答案 1 :(得分:1)

首先声明局部变量

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

然后引用局部变量而不是Model

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