MVC 4 Edit modal form using Bootstrap

前端 未结 4 1658
暖寄归人
暖寄归人 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:50

    I prefer to avoid using Ajax.BeginForm helper and do an Ajax call with JQuery. In my experience it is easier to maintain code written like this. So below are the details:

    Models

    public class ManagePeopleModel
    {
        public List People { get; set; }
        ... any other properties
    }
    
    public class PersonModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        ... any other properties
    }
    

    Parent View

    This view contains the following things:

    • records of people to iterate through
    • an empty div that will be populated with a modal when a Person needs to be edited
    • some JavaScript handling all ajax calls
    @model ManagePeopleModel
    
    

    Manage People

    @using(var table = Html.Bootstrap().Begin(new Table())) { foreach(var person in Model.People) { @person.Id @Person.Name @person.Age @html.Bootstrap().Button().Text("Edit Person").Data(new { @id = person.Id }).Class("btn-trigger-modal") } } @using (var m = Html.Bootstrap().Begin(new Modal().Id("modal-person"))) { } @section Scripts { }

    Partial View

    This view contains a modal that will be populated with information about person.

    @model PersonModel
    @{
        // get modal helper
        var modal = Html.Bootstrap().Misc().GetBuilderFor(new Modal());
    }
    
    @modal.Header("Edit Person")
    @using (var f = Html.Bootstrap.Begin(new Form()))
    {
        using (modal.BeginBody())
        {
            @Html.HiddenFor(x => x.Id)
            @f.ControlGroup().TextBoxFor(x => x.Name)
            @f.ControlGroup().TextBoxFor(x => x.Age)
        }
        using (modal.BeginFooter())
        {
            // if needed, add here @Html.Bootstrap().ValidationSummary()
            @:@Html.Bootstrap().Button().Text("Save").Id("btn-person-submit")
            @Html.Bootstrap().Button().Text("Close").Data(new { dismiss = "modal" })
        }
    }
    

    Controller Actions

    public ActionResult GetPersonInfo(int id)
    {
        var model = db.GetPerson(id); // get your person however you need
        return PartialView("[Partial View Name]", model)
    }
    
    public ActionResult UpdatePersonInfo(PersonModel model)
    {
        if(ModelState.IsValid)
        {
            db.UpdatePerson(model); // update person however you need
            return Json(new { success = true });
        }
        // else
        return PartialView("[Partial View Name]", model);
    }
    

提交回复
热议问题