Mat*_*ete 0 html c# asp.net-mvc-5
我已经看到了许多将从 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>
Run Code Online (Sandbox Code Playgroud)
如何将选择列表中的选定值向下传递到我的控制器,以便我可以将其添加到我的 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);
}
Run Code Online (Sandbox Code Playgroud)
模型:
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; }
}
Run Code Online (Sandbox Code Playgroud)
您应该将 select 的name属性设置为与控制器期望的参数名称相同的值。
[HttpPost]
public ActionResult Edit(string type)
{
//do work
}
Run Code Online (Sandbox Code Playgroud)
html:
<select id="Type" name="Type">
options...
</select>
Run Code Online (Sandbox Code Playgroud)
如果您要发布一个复杂的模型,例如
public class ViewModel
{
public string Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
到控制器:
[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
//do work
}
Run Code Online (Sandbox Code Playgroud)
select 的name属性应该等于模型的属性名称(“类型”也是如此)。
如果您出于某种原因不想遵循此约定,您还可以使用该Request.Form属性从控制器访问发布的值。
您还需要将动作的签名更改为
public ActionResult AddSection(Section NewSection, HttpPostedFileBase LogoFile)
Run Code Online (Sandbox Code Playgroud)
来绑定文件。
| 归档时间: |
|
| 查看次数: |
4303 次 |
| 最近记录: |