我在MVC 3创建页面中有一个下拉列表,但是当我发布页面时,我没有得到任何值。我的代码如下: -
查看: -
@using (Html.BeginForm("Create", "League", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ @ Html.ValidationSummary(真) 联赛
<div class="editor-label">
@Html.LabelFor(model => model.League.fk_CountryID, "Country")
</div>
<div class="editor-field">
@Html.DropDownList("fk_CountryID", "--Select One--") *
@Html.ValidationMessageFor(model => model.League.fk_CountryID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.League.LeagueName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.League.LeagueName)
@Html.ValidationMessageFor(model => model.League.LeagueName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.League.Image)
</div>
<div class="editor-field">
Upload File: <input type="file" name="Image" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
控制器: -
[HttpPost]
public ActionResult Create([Bind(Exclude = "Image")]Country country, HttpPostedFileBase Image, League league)
{
if (ModelState.IsValid)
{
model.League = league;
try
{
foreach (string file in Request.Files)
{
HttpPostedFileBase fileUploaded = Request.Files[file];
if (fileUploaded.ContentLength > 0)
{
byte[] imageSize = new byte[fileUploaded.ContentLength];
fileUploaded.InputStream.Read(imageSize, 0, (int)fileUploaded.ContentLength);
model.League.Image = imageSize;
}
}
db.Leagues.AddObject(model.League);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
ModelState.AddModelError("uploadError", e);
}
}
我做错了什么?无法获取控制器中的下拉列表值。
感谢您的帮助和时间
答案 0 :(得分:1)
确定通过在我的ViewModel中添加SelectList来修复它,如下所示: -
//Countries dropdown List
public SelectList CountryList { get; set; }
public string SelectedCountry { get; set; }
public LeagueData PopulateCountriesDDL(string selected, Country country)
{
var typeList = new SelectList(db.Countries.ToList(), "CountryID", "CountryName", selected);
LeagueData model = new LeagueData { CountryList = typeList, Country = country, SelectedCountry = selected };
return model;
}