我有一个自定义配置文件,其中包含我可能与MVC应用程序连接的一组数据库的基本信息。它是一个数据编辑应用程序,在我们搜索单个记录之前,用户选择包含他们要编辑的记录的数据库。为了创建用户将要使用的下拉菜单,我使用了以下类。键值是唯一的字符串,因为MuseSiteNumber对于列表中的多个项可能是相同的:
public class SiteSelection
{
public string Key { get; set; }
public string Description { get; set; }
public string DatabaseServer { get; set; }
public string DatabaseName { get; set; }
public int MuseSiteNumber { get; set; }
}
public class IndexViewModel
{
[Display(Name = "Select Site for Updates")]
public List<SiteSelection> MuseSites { get; set; }
[Required]
public SiteSelection SelectedSite { get; set; }
}
我在控制器中做的第一件事是将配置读入站点列表,然后将其加载到IndexViewModel中,并将其发送给下拉列表的视图。我的视图模型正在HttpGet中填充,但是当我试图获得所选值时,它返回为空。
我错过了什么?这是因为我不能使用字符串作为Key吗?
View: (Index.cshtml)
@model MuseCorrecter.Models.IndexViewModel
@{
@ViewBag.Title
}
<section>
<div class="content-wrapper">
<hgroup class="title">
@*<h2>@ViewBag.Message</h2>*@
</hgroup>
@using (Html.BeginForm())
{
@Html.DropDownListFor(h => h.SelectedSite, new SelectList(Model.MuseSites, "Key", "Description"), "Select one")
<div class="buttongroup" style="margin-top: 50px">
<input type="submit" name="submitButton" value="Select" />
<button type="button" onclick="location.href='@Url.Action("Index", "Home")'">Cancel</button>
</div>
}
</div>
</section>
Home Controller actions:
public class HomeController : Controller
{
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private ConfigReader ConfigReader { get; set; }
private List<SiteSelection> SelectableMuseSites { get; set; }
private List<SiteSelection> GetConfig()
{
ConfigReader = new ConfigReader();
Logger.DebugFormat(" Current Environment {0} ", ConfigReader.Profile.Key);
SelectableMuseSites = new List<SiteSelection>();
MuseSites ms = ConfigReader.MuseSites;
foreach (MuseSite s in ms)
{
SiteSelection ssvm = new SiteSelection();
ssvm.Key = s.Key;
ssvm.DatabaseName = s.DatabaseName;
ssvm.DatabaseServer = s.DatabaseServer;
ssvm.Description = s.Description;
ssvm.MuseSiteNumber = s.MuseSiteNumber;
SelectableMuseSites.Add(ssvm);
}
Logger.DebugFormat(" Number of sites available : {0}", SelectableMuseSites.Count());
return SelectableMuseSites;
}
[HttpGet]
public ActionResult Index()
{
ViewBag.Title = Constants.AppName;
ViewBag.Message = Constants.SiteSelectPrompt;
IndexViewModel ivm = new IndexViewModel();
// get the sites from the configuration file to populate the view model
ivm.MuseSites = GetConfig();
ViewBag.Message = ViewBag.Message + " (" + ConfigReader.Profile.Key.ToLower() + ")";
return View(ivm);
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
if (ModelState.IsValid)
{
if (model.SelectedSite != null)
{
Console.Write("Got here!");
}
}
return View();
}
}
保存到lambda表达式中的参数中。这里有视图模型。您需要做的是向视图模型中添加一个选定参数
public string Selected { get; set; }
然后在你的视图中改变你的lambda来查看那个值
@Html.DropDownListFor(h => h.Selected, new SelectList(Model.MuseSites, "Key", "Description"), "Select one")
在你的页面上,你可以通过设置Selected来预设下拉菜单,选择的值将被保存到该字段