我见过许多将从ViewModel生成的选择列表数据传递给MVC控制器的例子,但是我还没有看到如何从普通的<select>
HTML5标签传递选定的值。例如,在我的视图中我有:
<select id="Type">
<option value="Game">Game</option>
<option value="Collection">Collection</option>
<option value="Cinema">Cinema</option>
<option value="Book">Book</option>
</select>
如何将选择列表中的选定值传递给我的控制器,以便我可以将其添加到我的EF模型中?
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddSection(Section NewSection, HttpPostedFile LogoFile)
{
if (ModelState.IsValid)
{
try
{
if (LogoFile != null && LogoFile.ContentLength > 0)
{
if (LogoFile.ContentType == "image/png")
{
string FileName = NewSection.RouteName + "Logo";
NewSection.LogoFileID = FileUploadHelper.UploadSiteImage("Logos", FileName, LogoFile);
}
else
{
ModelState.AddModelError("File Type", "Logo Files must be PNG files.");
return View(NewSection);
}
}
using (db)
{
db.Sections.Add(NewSection);
db.SaveChanges();
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
ModelState.AddModelError("Processing Error", "There was a problem processing the new section, please try again later.");
return View(NewSection);
}
}
return View(NewSection);
}
型号:
public class Section
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int16 ID { get; set; }
public Int64? LogoFileID { get; set; }
[Required, MaxLength(250), Column(TypeName = "varchar")]
public string RouteName { get; set; }
[Required, MaxLength(15), Column(TypeName = "varchar")]
public string Type { get; set; }
[Required]
public string Title { get; set; }
public string Synopsis { get; set; }
[ForeignKey("LogoFileID")]
public virtual File Logo { get; set; }
}
答案 0 :(得分:4)
您应该将select的name
属性设置为与控制器所期望的参数名称相同的值。
[HttpPost]
public ActionResult Edit(string type)
{
//do work
}
HTML:
<select id="Type" name="Type">
options...
</select>
如果您要发布像
这样的复杂模型public class ViewModel
{
public string Type { get; set; }
}
到控制器:
[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
//do work
}
select的name
属性应该等于模型的属性名称(“Type”)。
如果由于某种原因不想遵循此约定,您还可以使用Request.Form
属性从控制器访问发布的值。
您还需要将操作的签名更改为
public ActionResult AddSection(Section NewSection, HttpPostedFileBase LogoFile)
绑定文件。