【发布时间】:2017-02-28 19:18:19
【问题描述】:
我在从 ASP.Net MVC 表单中获取 SelectListItem \ DropDwown 选定值的值时遇到了一些困难。
我已经检查了过去的答案并查看了这些但没有成功
- Get selected item in DropDownList ASP.NET MVC
- Asp.Net MVC with Drop Down List, and SelectListItem Assistance
我还检查了其他一些我现在无法回复的答案
我在控制器中的代码是
public ActionResult QuickSearch()
{
var ddlValues = new List<DropDownValues>
{
new DropDownValues { Text= "5", Value = 5},
new DropDownValues { Text= "10", Value = 5}
};
var model = new QuickSearchViewModel();
model.Distance = ddlValues.Select(x => new SelectListItem {Text = x.Text, Value = x.Value.ToString() });
//var model = new QuickSearchViewModel()
//{
// Distance = from value in ddlValues
// select new SelectListItem
// {
// Text = value.Text,
// Value = value.Value.ToString()
// }
//};
return PartialView(model);
}
[HttpPost]
public ActionResult QuickSearch(QuickSearchViewModel model)
{
if (ModelState.IsValid)
{
return RedirectToAction("QuickSearch", "Search", model);
}
return PartialView(model);
}
填充选择列表的代码运行良好,触发 HttpPost 事件的按钮也按预期运行。
但是对于我的生活,除非我使用 Ajax,否则我现在不想这样做,除非我必须这样做,因为我希望它从 Home Controller 重定向到 Search Controller。
这是局部视图的 Razor\HTML
@model SP.DABB.WebUI.Models.QuickSearchViewModel
@using(Html.BeginForm("QuickSearch", "Home", FormMethod.Post))
{
<div class="form-group">
<div class="col-md-6 col-lg-6">
@Html.LabelFor(x => x.PostCode)
</div>
<div class="col-md-6 col-lg-6">
@Html.TextBoxFor(x => x.PostCode, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-lg-6">
@Html.LabelFor(m => m.Distance, new { @class = "control-label" })
</div>
<div class="col-md-6 col-lg-6">
@Html.DropDownListFor(m => m.Distance, new SelectList(Model.Distance, "Value", "Text"), new { @class = "form-control" })
@*@Html.DropDownListFor(m => m.Distance, Model.Distance, new { @class = "form-control" })*@
</div>
</div>
<br /><br />
<div class="form-group">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 pull-right">
@*<input type="button" id="bttnQuickSearch" class="btn btn-info pull-right" value="Perform Quick Search"/>*@
<button type="submit" id="bttnQuickSearch" class="btn btn-info pull-right">Search</button>
</div>
</div>
}
--编辑--查看模型添加
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SP.DABB.WebUI.Models
{
public class QuickSearchViewModel
{
[Display(Name = "Your Postcode")]
[StringLength(maximumLength:8, MinimumLength = 5, ErrorMessage = "Please provide your full postcode.")]
public string PostCode { get; set; }
[Display(Name = "Distance")]
public IEnumerable<SelectListItem> Distance { get; set; }
public int SelectedDistance { get; set; }
public QuickSearchViewModel()
{
Distance = new List<SelectListItem>();
}
}
}
非常感谢任何和所有的帮助。
【问题讨论】:
标签: c# asp.net asp.net-mvc razor selectlistitem