2017-04-17 50 views
0

我有一個表單和兩個操作方法,我的操作方法使用相同的表單進行編輯和添加 我想基於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> 
} 
+0

你能證明你的觀點相關的HTML? –

回答

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"; 
     } 
    } 
} 

}