我有一个跟随控制器:
public class StoreController : Controller
{
public ActionResult Index(string category, int? page)
{
//some code
}
}
以及将数据发布到Index
方法的视图:
@using (Html.BeginForm("Index", "Store", new { category = Model.Category, page = 1}))
{
<input type = "submit" class="btn btn-default" value = "Search" />
@:Choose category:  
@Html.DropDownListFor(model => model.Category, new[]
{
new SelectListItem{ Text = "All", Value = "All", Selected = true},
new SelectListItem{ Text = "Cat1", Value = "Cat1"},
new SelectListItem{ Text = "Cat2", Value = "Cat2"},
new SelectListItem{ Text = "Cat3", Value = "Cat3"}
})
}
问题是,传递给Index
方法的路由值显然是错误的,因为Model.Category
是传递给视图的模型的类别。我尝试使用下拉列表中的选定值进行路由。问题是如何检索它?
我知道我可以用jquery Ajax做到这一切,但我想先用这种方式尝试。是否可以以简单的方式进行,或者我是否真的需要修改GET请求?
答案 0 :(得分:0)
你的模型应该是
public class MyModel
{
public string Category {get; set;}
public int? page {get; set;}
}
使用此
public class StoreController : Controller
{
[HttpPost]
public ActionResult Index(MyModel model)
{
// process ur submit page with proper category
}
[HttpGet]
public ActionResult Index()
{
var model = new MyModel();
model.Category = "All"; // the default category
return View();
}
}
以这种方式渲染下拉列表
@Html.DropDownListFor(model => model.Category, new[]
{
new SelectListItem{ Text = "All", Value = "All" }, // YOU DO NOT NEED TO KEEP THIS SELECTED, MVC DOES AUTO SELECT BASED ON PROPERTY VALUE
new SelectListItem{ Text = "Cat1", Value = "Cat1"},
new SelectListItem{ Text = "Cat2", Value = "Cat2"},
new SelectListItem{ Text = "Cat3", Value = "Cat3"}
})