C# ASP.NET MVC 5从另一个模型下拉列表
我刚刚开始学习MVC。我正在asp.NETMCV5中使用实体框架构建一个项目。我已经研究了许多线程,但我没有找到任何有助于解决我的问题。我有两种型号:C# ASP.NET MVC 5从另一个模型下拉列表,c#,asp.net-mvc-5,entity-framework-6,C#,Asp.net Mvc 5,Entity Framework 6,我刚刚开始学习MVC。我正在asp.NETMCV5中使用实体框架构建一个项目。我已经研究了许多线程,但我没有找到任何有助于解决我的问题。我有两种型号: 资源: public class Resource { [Key] public int Id { get; set; } [Required] public string Name { get; set; } public string Comments
资源:
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; }
}
资源类型:
public class ResourceType
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
问题是:在视图>资源>创建中,我想为对象ResourceType类型添加DropDownList,其值来自类ResourceType string Name创建.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")
}
资源控制器:
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 Controller放在这里有一个错误(Resource和ResourceType都是ResourceType)。先把它修好。
将此代码放入此处的部分,以呈现ViewBag中的select元素。类型:
在此之前,您必须填写ViewBag。在操作中键入,将ResourceController的第一个创建操作更改为:
它会成功的。我认为获得所需内容的最佳方法是创建一个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
}
public类CreateResourceViewModel
{
公共资源资源{get;set;}
public SelectList ResourceType{get;set;}//这将创建ResourceType列表
public int IdResourceType{get;set;}//这将用于选择所选资源类型的id。
public CreateResourceViewModel(Resource,ListresourceType)//创建构造函数
{
这个。资源=资源;
//在这里,您将列表设置为新的selectList,说明列表的来源。Id de ValueValue字段,名称为valuetextfield
this.ResourceType=新的选择列表(ResourceType,“Id”,“Name”);
}
public CreateResourceViewModel(){}//您需要第二个构造函数
}
现在,您需要一个createactionresult来接受资源控制器中的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);
}
}
//GET:Locals/Create
公共操作结果创建()
{
资源=新资源();
列出资源类型;
使用(yourcontext db=newyourcontext())
{
resourceType=db.resourceType.ToList();//用数据库中的resourceType填充列表
}
CreateResourceViewModel vm=new CreateResourceViewModel(resource,resourceType);//创建一个新的viewmodel,并为其提供我们创建的必要参数
返回视图(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果创建(CreateResourceViewModel vm)
{
使用(yourcontext db=newyourcontext())
{
if(ModelState.IsValid)
{
试一试{
vm.Resource.Type=db.ResourceTpe.Find(vm.IdResourceType);//使用视图中选择的ID在数据库中查找它
db.Resources.Add(vm.Resource);
db.SaveChanges();
返回操作(“索引”);
}
捕获(例外e)
{
e、 消息();
}
}
返回视图(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")
}
@model yourSolution.ViewModels.CreateResourceViewModel
@{
ViewBag.Title=“创建”;
}
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
资源
@Html.ValidationSummary(true,“,new{@class=“text danger”})
@LabelFor(model=>model.Name,htmlAttributes:new{@class=“controllabel col-md-2”})
@EditorFor(model=>model.Name,new{htmlAttributes=new{@class=“form control”})
@Html.ValidationMessageFor(model=>model.Name,“,new{@class=“text danger”})
@LabelFor(model=>model.Comments,htmlAttributes:new{@class=“controllabel col-md-2”})
@EditorFor(model=>model.Comments,new{htmlAttributes=new{@class=“form control”})
@Html.ValidationMessageFor(model=>model.Comments,“,new{@class=“text danger”})
@LabelFor(model=>model.ResourceType,htmlAttributes:new{@class=“controllabel col-md-2”})
//这就是创建包含所有资源类型的dropdownlist所需的内容
@Html.DropDownListFor(model=>model.IdResourceType,model.ResourceType,“--Select-->”)
@LabelFor(model=>model.IsActive,htmlAttributes:new{@class=“controllabel col-md-2”})
@EditorFor(model=>model.IsActive)
@Html.ValidationMessageFor(model=>model.IsActive,“,new{@class=“text danger”})
}
@ActionLink(“返回列表”、“索引”)
@节脚本{
@Scripts.Render(“~/bundles/jqueryval”)
}
希望这有帮助 -关键词是最小值
// 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);
}
}
@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")
}