如何根据动作方法名称更改标题表单?

时间:2017-04-17 11:49:42

标签: asp.net-mvc forms

我有一个表单和两个操作方法我的操作方法使用相同的表单进行编辑和添加 我想根据Action方法的名称更改表单标题。 例如,当我点击添加按钮电影时,表单的标题名称必须是“新电影”。 当我点击电影的编辑按钮时,表格的标题名称必须是“编辑电影”。

        public ActionResult New()
    {
        var geners=_context.Genres.ToList();
        var viewModel=new MovieFormViewModel
        {
            Genres=geners
        };
        //_context.Movies.Add(movie);
        return View("New", viewModel);
    }
     public ActionResult Edit(int id)
    {
        var movie=_context.Movies.SingleOrDefault(m => m.Id==id);
        if (movie == null)
            return HttpNotFound();
        var viewModel=new MovieFormViewModel
        {
            Movie=movie,
            Genres=_context.Genres.ToList()
        };

        return View("New",viewModel);
    }

 [HttpPost]
    public ActionResult Save(Movie movie)
    {
        movie.DateAdded = DateTime.Now;
        _context.Movies.Add(movie);
        _context.SaveChanges();
        return RedirectToAction("index", "Movies");
    }

=============================================== ===

@model Vidly.ViewModels.MovieFormViewModel
@{
    ViewBag.Title = "New";
}
<h2>New Movie</h2>
@using (@Html.BeginForm("Save", "Movies"))
{
    <div class="form-group">
        @Html.LabelFor(m =>m.Movie.Name)
        @Html.TextBoxFor(m => m.Movie.Name, new { @class = "form-control" })

    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Movie.ReleaseDate)
        @Html.TextBoxFor(m => m.Movie.ReleaseDate, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Movie.Genre)
        @Html.DropDownListFor(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Name"), "Select Genres", new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Movie.NumberInStock)
        @Html.TextBoxFor(m => m.Movie.NumberInStock, new { @class = "form-control" })
    </div>
    <button type="submit" class="btn btn-primary">Save</button>
}

1 个答案:

答案 0 :(得分:0)

我的问题已修复。

    public class MovieFormViewModel
{
    public IEnumerable<Genre> Genres { get; set; }
    public Movie Movie { get; set; }
    public string Title
    {
        get
        {
            if (Movie != null && Movie.Id != 0)
                return "Edit Movie";
            return "New Movie";
        }
    }
}

}