Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MVC4使用Bootstrap编辑模式表单_C#_Jquery_Ajax_Asp.net Mvc_Twitter Bootstrap - Fatal编程技术网

C# MVC4使用Bootstrap编辑模式表单

C# MVC4使用Bootstrap编辑模式表单,c#,jquery,ajax,asp.net-mvc,twitter-bootstrap,C#,Jquery,Ajax,Asp.net Mvc,Twitter Bootstrap,我正在使用MVC4和实体框架开发一个intranet web应用程序。我有一个可以通过编辑操作修改的人员列表。我想通过使用模态表单使我的应用程序更具动态性。因此,我尝试将编辑视图放入引导模式,对此我有两个问题: 我应该使用简单视图还是局部视图 我如何执行验证(实际上它可以工作,但它将我重定向到我的原始视图,因此不是模态形式) 我想我必须使用AJAX和/或jQuery,但我对这些技术还不熟悉。任何帮助都将不胜感激 编辑:我的索引视图: @model IEnumerable<BuSIMat

我正在使用MVC4和实体框架开发一个intranet web应用程序。我有一个可以通过编辑操作修改的人员列表。我想通过使用模态表单使我的应用程序更具动态性。因此,我尝试将编辑视图放入引导模式,对此我有两个问题:

  • 我应该使用简单视图还是局部视图
  • 我如何执行验证(实际上它可以工作,但它将我重定向到我的原始视图,因此不是模态形式)
我想我必须使用AJAX和/或jQuery,但我对这些技术还不熟悉。任何帮助都将不胜感激

编辑:我的索引视图:

@model IEnumerable<BuSIMaterial.Models.Person>

@{
    ViewBag.Title = "Index";
}


<h2>Index</h2>

<br />

<div class="group">
        <input type="button" value="New person" class="btn" onclick="location.href='@Url.Action("Create")';return false;"/>
        <input type="button" value="Download report" class="btn" onclick="location.href='@Url.Action("PersonReport")';return false;"/>
</div>


@using (Html.BeginForm("SelectedPersonDetails", "Person"))
{  
    <form class="form-search">
        <input type="text" id="tbPerson" name="tbPerson" placeholder="Find an employee..." class="input-medium search-query">
        <button type="submit" class="btn">Search</button>
    </form>
}


<table class="table">
    <thead>
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Start Date</th>
            <th>End Date</th>
            <th>Details</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
@foreach (BuSIMaterial.Models.Person item in ViewBag.PageOfPersons)
{
    <tr>
        <td>@item.FirstName</td>
        <td>@item.LastName</td>
        <td>@item.StartDate.ToShortDateString()</td>
        <td>
            @if (item.EndDate.HasValue)
            {
                @item.EndDate.Value.ToShortDateString()
            }        
        </td>

        <td>
            <a class="details_link" data-target-id="@item.Id_Person">Details</a>
        </td>

        <td>
            <div>
                <button class="btn btn-primary edit-person" data-id="@item.Id_Person">Edit</button>

            </div>
        </td>

    </tr>
    <tr>
        <td colspan="6">

            <table>
                <tr>
                    <th>National Number</th>
                    <td>@item.NumNat</td>
                </tr>
                <tr>
                    <th>Vehicle Category</th>
                    <td>@item.ProductPackageCategory.Name</td>
                </tr>
                <tr>
                    <th>Upgrade</th><td>@item.Upgrade</td>
                </tr>
                <tr>
                    <th>House to work</th>
                    <td>@item.HouseToWorkKilometers.ToString("G29")</td>
                </tr>
            </table>
            <div id="details_@item.Id_Person"></div>
        </td>

    </tr>

}
    </tbody>
</table>

<div class="modal hide fade in" id="edit-member">
    <div id="edit-person-container"></div>
</div>

@section Scripts
{
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/themes/base/css")

    <script type="text/javascript" language="javascript">

        $(document).ready(function () {

            $('#tbPerson').autocomplete({
                source: '@Url.Action("AutoComplete")'
            });

            $(".details_link").click(function () {
                var id = $(this).data("target-id");
                var url = '/ProductAllocation/ListByOwner/' + id;
                $("#details_"+ id).load(url);
            });

            $('.edit-person').click(function () {
                var url = "/Person/EditPerson"; 
                var id = $(this).attr('data-id');
                $.get(url + '/' + id, function (data) {
                    $('#edit-person-container').html(data);
                    $('.edit-person').modal('show');
                });
            });


        });

    </script>
}
@model IEnumerable
@{
ViewBag.Title=“Index”;
}
指数

@使用(Html.BeginForm(“SelectedPersonDetails”、“Person”)) { 搜寻 } 名字 姓氏 开始日期 结束日期 细节 行动 @foreach(查看包中的BusMaterial.Models.Person项目。PageOfPersons) { @item.FirstName @item.LastName @item.StartDate.ToShortDateString()文件 @if(item.EndDate.HasValue) { @item.EndDate.Value.ToShortDateString()的 } 细节 编辑 国家编号 @item.NumNat 车辆类别 @item.ProductPackageCategory.Name Upgrade@item.Upgrade 挨家挨户工作 @项目.房屋到工作公里数.到串(“G29”) } @节脚本 { @Scripts.Render(“~/bundles/jqueryui”) @style.Render(“~/Content/themes/base/css”) $(文档).ready(函数(){ $('#tbPerson')。自动完成({ 来源:'@Url.Action(“自动完成”)' }); $(“.details\u link”)。单击(函数(){ var id=$(this).data(“目标id”); var url='/ProductAllocation/ListByOwner/'+id; $(“#详细信息”+id).load(url); }); $('.edit person')。单击(函数(){ var url=“/Person/EditPerson”; var id=$(this.attr('data-id'); $.get(url+'/'+id,函数(数据){ $('#编辑个人容器').html(数据); $('.edit person').modal('show'); }); }); }); }
我的部分观点是:

@model BuSIMaterial.Models.Person

<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit</h3>
</div>
<div>

@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{

    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        <div class="editor-field">
            @Html.TextBoxFor(model => model.FirstName, new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-field">
            @Html.TextBoxFor(model => model.LastName, new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}
@model.material.Models.Person
×
编辑
@使用(Ajax.BeginForm(“EditPerson”、“Person”、FormMethod.Post、,
新选择
{
InsertionMode=InsertionMode.Replace,
HttpMethod=“POST”,
UpdateTargetId=“人员列表”
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.TextBoxFor(model=>model.FirstName,新的{maxlength=50})
@Html.ValidationMessageFor(model=>model.FirstName)
@Html.TextBoxFor(model=>model.LastName,新的{maxlength=50})
@Html.ValidationMessageFor(model=>model.LastName)
拯救
}

您应该使用局部视图。我采用以下方法:

使用视图模型,以便不将域模型传递给视图:

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; }
}
在您的
个人控制器中:

[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");
    }
}
接下来创建一个名为
\u EditPersonPartial
的局部视图。它包含模式页眉、正文和页脚。它还包含Ajax表单。它是强类型的,接受我们的视图模型

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}
@model Namespace.ViewModels.EditPersonViewModel
×
编辑组成员
@使用(Ajax.BeginForm(“EditPerson”、“Person”、FormMethod.Post、,
新选择
{
InsertionMode=InsertionMode.Replace,
HttpMethod=“POST”,
UpdateTargetId=“人员列表”
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.Bootstrap().ControlGroup().TextBoxFor(x=>x.Name)
@Html.Bootstrap().ControlGroup().TextBoxFor(x=>x.Age)
拯救
}

现在,在应用程序的某个地方,说另一个partial _peoplePartial.cshtml等:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

@foreach(模型中的var person.People)
{
编辑
}
//这是模态定义
$(文档).ready(函数(){
$('.edit person')。单击(函数(){
var url=“/Person/EditPerson”;//指向控制器的url
var id=$(this.attr('data-id');//给列表中每个按钮的id
$.get(url+'/'+id,函数(数据){
$('#编辑个人容器').html(数据);
$(“#编辑人”).modal('show');
});
});
});

我宁愿避免使用
Ajax.begin
helper,并使用JQuery进行Ajax调用。根据我的经验,维护这样编写的代码更容易。详情如下:

型号

public class ManagePeopleModel
{
    public List<PersonModel> 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
}
控制器动作

public class ManagePeopleModel
{
    public List<PersonModel> 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
}
public ActionResult GetPersonInfo(int-id)
{
var model=db.GetPerson(id);//根据需要获取您的人员
返回部分视图(“[部分视图名称]”,模型)
}
公共行动结果更新personinfo(PersonModel模型)
{
if(ModelState.IsValid)
{
db.UpdatePerson(model);//根据需要更新person
返回Json(新的{success=true});
}
//否则
重新
@model ModelView
@{
    var item = Model;
}
<div class="row">
        // some data 
        <button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
</div>
@model Model
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <h4 class="modal-title" id="editor-title">Title</h4>
</div>
@using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "editor-success-" + @Model.Id,
                        OnSuccess = "success",
                        OnFailure = "failure",
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.Id)
    <div class="modal-body">
        <div class="form-horizontal">
            // Models input fields
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-primary">Save</button>
    </div>
}
[HttpGet]
public async Task<ActionResult> EditPartData(Guid? id)
{
    // Find the data row and return the edit form
    Model input = await db.Models.FindAsync(id);
    return PartialView("EditModel", input);
}

[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> MyEditAction([Bind(Include =
   "Id,Fields,...")] ModelView input)
{
    if (TryValidateModel(input))
    {  
        // save changes, return new data row  
        // status code is something in 200-range
        db.Entry(input).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return PartialView("dataRowView", (ModelView)input);
    }

    // set the "error status code" that will redisplay the modal
    Response.StatusCode = 400;
    // and return the edit form, that will be displayed as a 
    // modal again - including the modelstate errors!
    return PartialView("EditModel", (Model)input);
}
        bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
                    "~/Scripts/jquery.unobtrusive-ajax.js"));