[英]ASP.NET MVC 5 DropDownList from another model
我刚刚开始使用MVC。 我正在使用实体框架在asp.net mcv 5中构建一个项目。 我研究了许多线程,但是没有找到任何有助于解决我的问题的东西。 我有两个模型:
资源:
public class Resource
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Comments { get; set; }
[Required]
public ResourceType Type { get; set; }
public bool IsActive { get; set; }
}
的ResourceType:
public class ResourceType
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
问题是:在“视图”>“资源”>“创建”中,我想使用对象类ResourceType 字符串名称中的值为对象ResourceType Type添加DropDownList
Create.cshtml :
@model NetAudit.Models.Resource
@{
ViewBag.Title = "Create Resource";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Resource</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Comments, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Comments, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Comments, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
HERE
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.IsActive)
@Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to list", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
RecourceType控制器:
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using NetAudit.Models;
namespace NetAudit.Controllers
{
public class ResourceTypesController : BaseController
{
private readonly ApplicationDbContext _db = new ApplicationDbContext();
[Authorize]
public ActionResult Index()
{
return View(_db.ResourceTypes.ToList());
}
[Authorize]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ResourceType resourceType)
{
if (ModelState.IsValid)
{
_db.ResourceTypes.Add(resourceType);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(resourceType);
}
[Authorize]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ResourceType resourceType)
{
if (ModelState.IsValid)
{
_db.Entry(resourceType).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(resourceType);
}
[Authorize]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
_db.ResourceTypes.Remove(resourceType);
_db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
资源控制器:
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using NetAudit.Models;
namespace NetAudit.Controllers
{
public class ResourceTypesController : BaseController
{
private readonly ApplicationDbContext _db = new ApplicationDbContext();
[Authorize]
public ActionResult Index()
{
return View(_db.ResourceTypes.ToList());
}
[Authorize]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ResourceType resourceType)
{
if (ModelState.IsValid)
{
_db.ResourceTypes.Add(resourceType);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(resourceType);
}
[Authorize]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ResourceType resourceType)
{
if (ModelState.IsValid)
{
_db.Entry(resourceType).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(resourceType);
}
[Authorize]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
_db.ResourceTypes.Remove(resourceType);
_db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
我花了很多时间寻找解决这个问题的方法。 感谢您对此的反馈。
首先,您有一个错误将资源控制器放在这里(Resource和ResourceType均为ResourceType)。 首先修复它。
将以下代码放入“ 此处”部分,以呈现ViewBag.Types中的select元素:
@Html.DropDownListFor(m => m.Type.Id, (SelectList)ViewBag.Types, new
{
@class = "form-control"
});
在您必须在操作中填充ViewBag.Types之前,将ResourceController的第一个Create操作更改为:
[Authorize]
public ActionResult Create()
{
ViewBag.Types = new SelectList(_db.ResourceTypes.ToList(), "Id", "Name", "0");
return View();
}
它将起作用。
我认为获得所需内容的最佳方法是创建一个ViewModel,这使您可以创建具有各种类的视图。
在您的解决方案下,创建一个名为ViewModels的新文件夹。 创建一个新类,并将其命名为CreateResourceViewModel。
public class CreateResourceViewModel
{
public Resource Resource {get;set;}
public SelectList ResourceType {get;set;} //this will create the list of resourcetypes
public int IdResourceType {get;set;} //this will be used to select the id of resourceType you are selecting.
public CreateResourceViewModel (Resource resource,List<ResourceType>resourceType) //create a constructor
{
this.Resource = resource;
//here you will set the list as a new selectList, stating where the list will come from. the Id de valuevaluefield, and the name is the valuetextfield
this.ResourceType= new SelectList(resourceType,"Id","Name");
}
public CreateResourceViewModel(){} //you need this second constructor
}
现在,您需要一个Create ActionResult,它可以在资源控制器中接受ViewModel
// GET: Locals/Create
public ActionResult Create()
{
Resource resource = new Resource();
List<ResourceType> resourceType;
using (yourcontext db = new yourcontext())
{
resourceType = db.ResourceType.ToList(); //fill your list with the resourceTypes that are in your database
}
CreateResourceViewModel vm = new CreateResourceViewModel(resource,resourceType); //create a new viewmodel and give it the parameters necesary that we created
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateResourceViewModel vm)
{
using (yourcontext db = new yourcontext())
{
if (ModelState.IsValid)
{
try {
vm.Resource.Type = db.ResourceTpe.Find(vm.IdResourceType); //using the ID selected in the view find it in the database
db.Resources.Add(vm.Resource);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
e.Message();
}
}
return View(vm);
}
}
现在进入ViewModel的视图
@model yourSolution.ViewModels.CreateResourceViewModel
@{
ViewBag.Title = "Create";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Resource</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Comments, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Comments, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Comments, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ResourceType, htmlAttributes: new { @class = "control-label col-md-2" })
//this is what you need to create a dropdownlist with all the resourceTypes
<div class="col-md-10">
@Html.DropDownListFor(model => model.IdResourceType, Model.ResourceType,"--Select--" )
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.IsActive)
@Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to list", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
希望这可以帮助!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.