我正在製作一個具有下拉菜單的視圖。該觀點與CategoryModel看起來像這樣提供:返回到控制器中的操作時,已過帳的DDL列表爲空
public class CategoryModel
{
[Required]
[Display(Name = "Categories")]
public List<Category> Categories { get; set; }
[Required]
[GreaterThan(ExceedValue = 0, ErrorMessage = "Please select a category.")]
[Display(Name = "SelectedCategoryId")]
public int SelectedCategoryId { get; set; }
}
分類的列表視圖中使用,採取先分類來填充下拉列表並把它們放到一個的SelectList,像這樣:
@model RatingMVC3.Models.CategoryModel
@{
Layout = "~/Views/Shared/_MainLayout.cshtml";
ViewBag.Title = "Upload";
}
<h2>Upload</h2>
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
@Html.DropDownListFor(m => m.SelectedCategoryId, new SelectList(Model.Categories, "Id", "Description"), "-- Select Category --");
@Html.ValidationMessageFor(m => m.SelectedCategoryId);
@Html.HiddenFor(m => m.Categories);
}
當提交此表單並將模型返回給Controller時,我可以看到該模型返回到Controller中,但它包含一個空List,而不是View中存在的Categories列表。 (SelectedCategoryId如預期的那樣)。這是在控制器中的ActionResult方法:
[HttpPost]
[Authorize]
public ActionResult Upload(HttpPostedFileBase file, CategoryModel model)
{
if (ModelState.IsValid)
{
if (file != null && file.ContentLength > 0)
{
var FileExtension = Path.GetExtension(file.FileName);
string Path1 = null;
string FileName = null;
do
{
var randomName = Path.GetRandomFileName();
FileName = Path.ChangeExtension(randomName, FileExtension);
Path1 = Path.Combine(Server.MapPath("~/Images"), FileName);
} while (System.IO.File.Exists(Path1));
file.SaveAs(Path1);
if (UploadService.SaveImage(FileName, System.Web.HttpContext.Current.User.Identity.Name, model.SelectedCategoryId))
{
return RedirectToAction("Uploaded", "Upload");
}
}
return RedirectToAction("Index", "Home");
}
return View(model);
}
空表對我來說是一個問題,因爲你可以看到,如果ModelState中是無效的,視圖將被用相同型號又回來了,需要填充類別。 我希望有人能回答這個;)我會很樂意指定更多的信息,如果需要的話,在此先感謝
是否在所有類別的GET之後填充下拉菜單? – 2012-03-17 14:50:59
類別在GET操作方法中獲取並放入模型中,並且隨着View在GET方法中返回,模型(包含列表)將作爲參數傳遞給View,其中Dropdown是填充。 [Authorize] public ActionResult上傳() { CategoryModel CategoryModel1 = UploadService.GetCategories(); return View(CategoryModel1); } – emin 2012-03-17 17:21:02