2017-05-06 11 views
-1

MVCを使い始めたばかりです。私はエンティティフレームワークを使用してasp.net mcv 5でプロジェクトを構築しています。私は多くのスレッドを研究しましたが、私の問題を解決するのに役立つものは何も見つかりませんでした。私は2つのモデルがあります:
リソース:他のモデルの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; } 
    } 

そして、問題がある:[表示]> [リソースでは>私はからの値を持つオブジェクトResourceTypeがタイプのためのDropDownListを追加したい作成クラスResourceType 文字列名
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) - キーワードは** minimal **です。 –

答えて

0

ここでは、リソース・コントローラーをここに配置する際に間違いがあります(ResourceTypeとResourceTypeはどちらもResourceTypeです)。まずそれを修正してください。ここでセクションViewBag.Typesからselect要素レンダリングするために、このコードに入れて

:それはあなたが行動にViewBag.Typesを満たさなければならない前に

@Html.DropDownListFor(m => m.Type.Id, (SelectList)ViewBag.Types, new 
          { 
           @class = "form-control" 
          }); 

を、 ResourceControllerの最初の作成アクションを次のように変更します。

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

これが役に立てば幸いでのViewModelを受け入れる作成のActionResultを必要とします!