0

我不确定如何实现这一点,我在 Controllers 文件夹中有一个 MovieController.cs,在 Models 文件夹中有一个 MovieCreateViewModel.cs。我需要为创建、编辑和删除视图添加验证。

MovieDetailsViewModel.cs

public class MovieDetailsViewModel
{
    public int Id { get; set; }
 }     

然后我有 MovieController.cs

public class MovieController : Controller
{

    Connect connection;
    MovieCreateViewModel movie;
    MovieDetailsViewModel id;

    public MovieController()
    {
        this.connection = new Connect();
        this.movie = new MovieCreateViewModel();
        this.id = new MovieDetailsViewMode();
    } 

    public ActionResult Edit(MovieDetailsViewModel id)
    {
        movie = this.connection.MovieContext.Where(m => m.ID == id).SingleOrDefault();  **//I get an error here**
        return View(movie);
    }

    //
    // POST: /Movie/Edit/5

    [HttpPost]
    public ActionResult Edit(MovieCreateViewModel movieedit)
    {
        try
        {
            if (ModelState.IsValid)
            {
                this.connection.MovieContext.AddObject(movieedit);
                this.connection.MovieContext.Context.SaveChanges();
                return RedirectToAction("Index");
            }

        }
        catch
        {
            return View(movieedit);
        }
    }

对于httpPost,我MovieDetailsViewModel id在参数列表中输入了类型,请问我从哪里开始?

谢谢

4

2 回答 2

1

现在将对您的模型实例执行验证,要检查它,您可以:

ModelState.IsValid

在保存操作之前的控制器方法中。只要视图上的输入名称与模型类的属性名称相对应,绑定和验证就会在执行操作方法之前隐式执行。要在视图中显示验证消息,请将 Html.ValidationMessage() 添加到视图顶部。希望这可以帮助。顺便说一句,它非常值得一试Foolproof Validation,它提供了条件验证属性和其他一些好东西。

于 2012-07-13T08:14:36.533 回答
0

更好的做法是使用单独的模型和视图模型。将您的模型转换为视图模型,然后将其传递给视图

public ActionResult Edit(int id)
{
     var movie = this.connection.MovieContext.SingleOrDefault(m => m.ID == id);
     var vm = new MovieCreateViewModel{ Id = movie.Id};
     return View(vm);
}

//
// POST: /Movie/Edit/5

[HttpPost]
public ActionResult Edit(MovieCreateViewModel vm)
{
    try
    {
        if (ModelState.IsValid)
        {
            var movie = new Movie{Id = vm.Id};
            this.connection.MovieContext.Attach(movie);
            this.connection.MovieContext.Context.SaveChanges();
            return RedirectToAction("Index");
        }

    }
    catch
    {
        return View(movieedit);
    }
}
于 2012-07-13T08:53:20.930 回答