0


저는 MVC의 초보자이고 프로젝트에 몇 가지 문제가 있습니다. 내가 뭘 하려는지는 렌트카를 사용자가 편집 할 수있는 플랫폼입니다.
ASP.NET의 MVC - 드롭 다운 목록을 사용하여 데이터베이스 및 뷰 디자인

  • 데이터베이스
  • 등록/로그인
  • 에있는 모든 자동차의 드롭 다운 목록에 새 차를 임대 요청을 추가 데이터베이스
  • 에 자동차를 추가 : 내 프로젝트에서 내가 좋아하는 옵션을 가지고 싶습니다 데이터베이스에있는 차의 각 임대 요청
  • 보기 역사는

프로젝트는 엔티티 프레임 워크 *하여 .sdf 데이터베이스를 기반으로한다. 나는 모델/디렉토리에 클래스 파일을 만들었 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Data.Entity; 
namespace MVC4.Models 
{ 
    public class Car 
    { 
    public int ID {get; set;} 
    public string Make {get; set;} 
    public string Model {get; set;} 
    public virtual ICollection<Car> Cars{ get; set; } 
    } 

    public class Request 
    { 
    public int ID {get; set;} 
    public string User {get; set;} 
    public int CarID{ get; set; } 
    public virtual Car Car { get; set; } 
    } 

    public class CarDBContext : DbContext 
    { 
    public DbSet<Car> Cars { get; set; } 
    public DbSet<Request> Requests { get; set; } 
    } 
} 

컨트롤러 :

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.Entity; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using MVC4.Models; 

namespace MVC4.Controllers 
{ 
public class RequestController : Controller 
{ 
    private CarDBContext db = new Car1DBContext(); 

    // 
    // GET: /Request/ 

    public ViewResult Index() 
    { 
     return View(db.Requests.ToList()); 
    } 

    // 
    // GET: /Request/Details/5 

    public ViewResult Details(int id) 
    { 
     Wypozyczenie1 Request = db.Requests.Find(id); 
     return View(request); 
    } 

    // 
    // GET: /Request/Create 

    public ActionResult Create() 
    { 
     return View(); 
    } 

    // 
    // POST: /Request/Create 

    [HttpPost] 
    public ActionResult Create(Request request) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Requests.Add(request); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(request); 
    } 

    // 
    // GET: /Request/Edit/5 

    public ActionResult Edit(int id) 
    { 
     Request request= db.Requests.Find(id); 
     return View(request); 
    } 

    // 
    // POST: /Request/Edit/5 

    [HttpPost] 
    public ActionResult Edit(Request requests) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Entry(request).State = EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(request); 
    } 

    // 
    // GET: /Request/Delete/5 

    public ActionResult Delete(int id) 
    { 
     Request request= db.Requests.Find(id); 
     return View(request); 
    } 

    // 
    // POST: /Request/Delete/5 

    [HttpPost, ActionName("Delete")] 
    public ActionResult DeleteConfirmed(int id) 
    {    
     Request request = db.Requests.Find(id); 
     db.Requests.Remove(request); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

    protected override void Dispose(bool disposing) 
    { 
     db.Dispose(); 
     base.Dispose(disposing); 
    } 
} 
} 

요청보기 만들기 :이 나를 위해 작동하지 않습니다

........ 

<div class="editor-field"> 
    ViewBag.PossibleCategories = context.Cars; 
@Html.DropDownListFor(model => model.ID, 
    ((IEnumerable<MVC4.Models.Car>)ViewBag.PossibleCategories) 
    .Select(option => new SelectListItem { 
    Text = (option == null ? "None" : option.Make), 
    Value = option.ID.ToString(), 
    Selected = (Model != null) && (option.ID == Model.CarID) 
}), "Choose...") 
@Html.ValidationMessageFor(model => model.CarID) 

</div> 
.......... 

. 이 드롭 다운을 채우고이 뷰에서 데이터를 데이터베이스에 삽입하는 방법은 무엇입니까? 도움 주셔서 감사합니다. 나는 이것에 많은 시간을 보내고 그것을 이해할 수 없다. 내 영어로 미안해, 너희들이 나를 이해하기를 바란다.

내가 얻을 오류 :이 내 요청/전망이다

Value cannot be null. 
Parameter name: source. 


Description: An unhandled exception occurred during the execution of the 
current web request. Please review the stack trace for more 
information about the error and where it originated in the code. 

Exception Details: System.ArgumentNullException: Value cannot be null. 
Parameter name: source 

Source Error: 


Line 32:   <div class="editor-field"> 
Line 33:   ViewBag.PossibleCategories = context.Cars; 
Line 34:  @Html.DropDownListFor(model => model.ID, 
Line 35:   ((IEnumerable<MVC6.Models.Car>)ViewBag.PossibleCategories) 
Line 36:   .Select(option => new SelectListItem { 

: 나는 드롭 다운리스트가 너무 가야 그것을 힘든 강타의 비트를 발견

@model IEnumerable<MVC6.Models.Request> 

@{ 
ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<p> 
@Html.ActionLink("Create New", "Create") 
</p> 
<table> 
<tr> 
    <th> 
     User 
    </th> 
    <th> 
     Car 
    </th> 
    <th></th> 
</tr> 

@foreach (var item in Model) { 
<tr> 
    <td> 
     @Html.DisplayFor(modelItem => item.User) 
    </td> 
    <td> 
     @Html.DisplayFor(modelItem => item.Car.Make) 
    </td> 
    <td> 
     @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | 
     @Html.ActionLink("Details", "Details", new { id=item.ID }) | 
     @Html.ActionLink("Delete", "Delete", new { id=item.ID }) 
    </td> 
</tr> 
} 

</table> 
+2

* 제대로 작동하지 않습니다. * 문제 설명이별로 없습니다. 이것이 의미하는 바가 무엇인지 설명하는 질문을 개선하시기 바랍니다. 예상되는 결과와 실제 결과는 무엇입니까? –

+0

나는 내가 얻은 오류의 desctiption을 추가했습니다. 도와 주셔서 감사합니다. – user1447748

+0

언제 오류가 발생합니까? 보기가 렌더링되거나 (GET) 제출 단추 (POST)를 클릭하면? – Slauma

답변

0

,하지만 난 그것을 알아 냈다 마침내 ...

평소와 같이 몇 가지 방법이 있습니다. 나는 selectList의를 작성한 컨트롤러에서

과 ViewBag 내보기에 그런

ViewBag.mylist = new SelectList(db.Whatever, "ValueColumn", "DisplayColumn");

에 넣어 : 여기 어떻게 내가 해냈어

Html.DropDownList("myname", (SelectList)ViewBag.mylist, "Select Something", 

    new 
    { 
     @onchange = "form.submit();" 
    }) 

당신의 양식을 넣을 경우 그러면 필요한 경우 양식을 게시합니다. ViewModel에서도 이런 종류의 작업을 수행 할 수 있다고 생각합니다. 이것은 나를 위해 가장 쉬운 방법처럼 보였습니다. 조금 어수선했지만. 의견을 듣고 기쁘게.

관련 문제