【发布时间】:2014-06-30 01:50:44
【问题描述】:
我正在尝试添加多行数据并将其传递到数据库中的表以及另一个项目到不同的表。下面是数据库的结构:
User Table
userid
name
Movie Table
Movieid
userid
moviename
Cinema Table
Movieid
cinemaid
location
time
movietable 与 Cinema 表有一对多的关系。用户表有一个,我有四个不同的视图模型与之关联:
UserViewModel
{
public int userid;
public string name;
}
MoviewViewModel
{
public int movieid;
public int userid;
public string moviename;
public List<CinemaViewModel> cinema;
}
CinemaViewModel
{
public int movieid;
public int cinemaid;
public string location;
public string time;
}
UserandMovieViewModel
{
public List<MoviewViewModel> movie;
public UserViewModel user;
}
我将 userandmoviewmodel 从控制器创建传递到视图,并想为用户和电影添加一个条目,但想从该单个页面向 Cinema 数据库添加多个条目。当我向电影院添加一个条目时,它工作正常。但是,我希望能够在发布表单时向电影院表添加多个条目。我已经尝试过下面的教程,但这似乎不适用于创建。
http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/
编辑
给出空异常的代码
<ul id="movieEditor" style="list-style-type: none">
@foreach (CinemaViewModel cinemamodel in Model.UserandMovieViewModel.cinema) {
Html.RenderPartial("MovieEntryEditor", cinemamodel);
}
</ul>
<a id="addAnother" href="#">Add another</a>
EDIT2
创建控制器代码
[httpget]
public ActionResult Create()
{
UserViewModel usermodel = new UserviewModel();
List<MovieViewModel> moviemodel= new List<MovieViewModel>();
UserandMovieViewModel model = new UserandMovieViewmodel{user = usermodel, movie=moviemodel }
return View(model)
}
[httppost]
public ActionResult Create(UserandMovieViewmodel model)
{
IRepository<User> userrep = new ApplicationRepository<User>();
IRepository<Movie> userrep = new ApplicationRepository<Movie>();
IRepository<Cinema> userrep = new ApplicationRepository<Cinema>();
User user = null;
Movie movie = null;
Cinema cinema = null;
UserViewModel usermodel = model.usermodel;
MovieViewModel moviemodel= model.moviemodel;
CinemaViewModel cinemamodel = model.moviemodel.cinema;
if(ModelState.valid)
{
user = new user();
user.name = usermodel.name;
userrep.add(user);
movie = new movie();
movie.userid = user.userid; (gets from database as its autoappend)
movie.moviename = moviemodel.moviename;
movierep.Add(movie);
cinema = new cinema();
cinema.movieid = movie.movieid;
cinema.location = cinemamodel.location;
cinema.time = cinemamodel.time;
cinemarep.Add(cinema);
}
return View(model);
}
我已经从内存中编写了代码,因为我目前没有它。请更正您看到的任何错误。
编辑 3
局部视图
@model Application.ViewModels.CinemaViewModel
<li style="padding-bottom:15px">
<div style="width: 450px; float: left;">
<label class="location">
Location
</label>
<span style="margin-left: 26px;">
@Html.TextBoxFor(model => model.location)
@Html.ValidationMessageFor(model => model.location)
</span>
<span>
@Html.TextBoxFor(model => model.time)
@Html.ValidationMessageFor(model => model.time)
</span>
</div>
【问题讨论】:
-
你遇到了什么问题?
-
当我用它来创建时,它给了我一个系统空异常。我希望能够在创建用户和电影期间添加许多电影列表。
-
能否请您发布给您空引用异常的代码?
-
我已经添加了代码。
标签: c# sql entity-framework asp.net-mvc-5