MVC 4 Edit modal form using Bootstrap

前端 未结 4 1653
暖寄归人
暖寄归人 2020-11-29 16:41

I\'m using MVC 4 and Entity Framework to develop an intranet web application. I have a list of persons which can be modify by an edit action. I wanted to make my app more dy

4条回答
  •  攒了一身酷
    2020-11-29 16:54

    You should use partial views. I use the following approach:

    Use a view model so you're not passing your domain models to your views:

    public class EditPersonViewModel
    {
        public int Id { get; set; }   // this is only used to retrieve record from Db
        public string Name { get; set; }
        public string Age { get; set; }
    }
    

    In your PersonController:

    [HttpGet] // this action result returns the partial containing the modal
    public ActionResult EditPerson(int id)
    {  
        var viewModel = new EditPersonViewModel();
        viewModel.Id = id;
        return PartialView("_EditPersonPartial", viewModel);
    }
    
    [HttpPost] // this action takes the viewModel from the modal
    public ActionResult EditPerson(EditPersonViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            var toUpdate = personRepo.Find(viewModel.Id);
            toUpdate.Name = viewModel.Name;
            toUpdate.Age = viewModel.Age;
            personRepo.InsertOrUpdate(toUpdate);
            personRepo.Save();
            return View("Index");
        }
    }
    

    Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

    @model Namespace.ViewModels.EditPersonViewModel
    
    
    @using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post, new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", UpdateTargetId = "list-of-people" })) { @Html.ValidationSummary() @Html.AntiForgeryToken() }

    Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

    @foreach(var person in Model.People) { }
    // this is the modal definition

提交回复
热议问题