2017-05-06 34 views
-1

我剛剛開始使用MVC。我正在使用實體框架在asp.net mcv 5中構建一個項目。我研究了很多線程,但是我沒有找到任何有助於解決問題的方法。我有兩個型號:
資源:ASP.NET MVC 5從另一個模型的DropDownList

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; } 
    } 

而問題是:在查看>資源>創建我想從值添加DropDownList中的對象的ResourceType類型 class ResourceType string Name
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); 
     } 
    } 
} 

我花了很多時間尋找一個解決這個問題。我很感謝你對此的反饋。

+0

[如何創建一個最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve) - 關鍵詞是**最小** –

回答

0

你們之間有一個錯誤,把資源控制器放在這裏(Resource和ResourceType都是ResourceType)。首先修復它。

放在這裏這部分代碼從ViewBag.Types渲染選擇元素:

@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(); 
     } 

它會工作。

0

我認爲得到你想要的最好的方法是創建一個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 

} 

現在,你需要接受一個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); 
     } 
    } 

現在到視圖視圖模型

@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") 
    } 

希望這有助於創建的ActionResult!