简体   繁体   English

从Modal Bootstrap MVC 4 + JQuery插入数据(发布方法)

[英]Insert Data from Modal Bootstrap MVC 4 + JQuery (Post Method)

I have a modal form that save me on certain data information, work correctly, but I need to update a in my view with the response and doesn't work correctly and bring me a list without format and class css, like when an error occurs, the modal disappears and brings back a page without css with all the validates error, what I have wrong in my code or that I do to fix it? 我有一个模式形式的表单,可以保存某些数据信息,可以正常工作,但是我需要在响应中更新视图,并且不能正常工作,并为我提供一个不带格式和类css的列表,例如发生错误时,模态消失,并返回一个没有CSS的页面,并显示所有validates错误,我的代码有什么错误或者我要解决此错误?

My Partial View 我的局部视图

@model ControlSystemData.Models.Tourist


<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel-Update">Ingresar Turista</h4>
</div>

@using(@Html.BeginForm("Create","Tourist", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <div class="modal-body" style="text-align:center; padding:10px;">
            @if (!string.IsNullOrWhiteSpace(ViewBag.Error))
            {
                <div class="alert alert-danger alert-dismissable" id="danger">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    @ViewBag.Error
                </div>
            }
            <div class="panel-body">

                <div class="form-group">
                    @Html.TextBoxFor(u => u.Name, new { @class = "form-control", @placeholder = "Nombre del Pasajero" })
                    @Html.ValidationMessageFor(u => u.Name)
                </div>

               @*More Data Here*@

            </div>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-primary">Guardar</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
        </div>
    </fieldset>
}

My Modal Bootstrap 我的模态引导

<!--Modal Tourist-->
<div class="modal fade" id="Modal-Tourist" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <p class="body">

            </p>
        </div>
    </div>
</div>
<!--End Modal Tourist-->

My Controller 我的控制器

[HttpPost]
public ActionResult Create(Tourist collection)
{
    if (ModelState.IsValid)
    {
        db.Tourist.Add(collection);
        db.SaveChanges();
        return RedirectToAction("IndexByEventsTourist", "Tourist", new { id = collection.id });
    }


    Response.StatusCode = 400;
    return PartialView("Create", collection);
}

My Script 我的剧本

<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">

    function clearErrors() {
        $('#msgErrorNewTourist').html('');
        $('#alert').html('');
    }

    function writeError(control, msg) {
        var err_msg = '<div class="alert-message error"><a class="close" href="#">×</a><p>' + msg + '</p></div>';
        $('#' + control).html(err_msg);
    }

    $(document).ready(function () {                
        $('#Modal-Tourist form').on('submit', function () {            
            if ($(this).valid()) {
                $.ajax({
                    url: '@Url.Action("Create","Tourist")',
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#Modal-Tourist').modal('hide');
                        $("#eventsDetailsList").html(result);
                    },
                    error: function (err) {
                        writeError('body', 'Wrong Data');
                    }
                });
            }
            return false;
        });

        function getRequest(url) {
            jQuery.noConflict();
            $.ajax({
                url: url,
                context: document.body,
                success: function (data) {
                    $('.modal-content p.body').html(data);                    
                    $('#Modal-Tourist').modal('show');
                    $('#Name').focus();
                },
                error: function (err) {
                    writeError('msgErrorNewTourist', err.responseText);
                }
            });
        }


        $('a.newTourist').click(function () {           
            var id = $(this).attr("eventsid");
            var url = '@Url.Content("~/Tourist/Create")/' + id;

            getRequest(url);

            return false;

        });
    });
</script>

I need that the modal stay in your position with your errors or rendering my correctly with the update. 我需要模式保留在您的错误位置,或者通过更新正确呈现我的位置。

Thanks 谢谢

Images 图片 页面正确呈现 来自我的控制器的模态错误(在新页面中,不在您的主要阶段) 更新成功但未正确更新页面中的div

RedirectToAction RedirectToAction

public ActionResult IndexByEventsTourist(int id)
{
    ViewBag.id = id;
    var eventsById = db.Events.Where(u => u.id == id).FirstOrDefault();
    ViewBag.Events = eventsById;

    var touristByEvent = db.Tourist.Where(u => u.id == id).Include(u => u.Events).ToList();
    ViewBag.TouristByEvent = touristByEvent;

    return PartialView("IndexByEvents", touristByEvent);
}

Parent page (Render Div with the Partial Render or Update from Modal) 父页面(带有部分渲染的渲染Div或从模态更新)

    <div class="col-lg-8">
        <div class="panel panel-default">
            <div class="panel-heading">                
                <a href="@Url.Action("Create", "Tourist", new { id = Model.id })" eventsid="@Model.id" class="btn btn-primary newTourist"><i class="fa fa-plus"></i> Add</a>               
            </div>
            <div class="panel-body">
                <div class="row">
                    <div id="msgErrorNewTourist"></div>
                    <div class="col-lg-12" id="eventsDetailsList">                        
                            @{Html.RenderAction("IndexByEventsTourist", "Tourist", new { id = Model.id });}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

After many tries, I changed the <script></script> (my script it was very obsolete) and I modified the <script> of this answer for my intent of load content dynamically and Validate the form before Post, Many Thanks to Sthepen Muecke for provide me a solution and clarify my issues... Thank you so much. 经过多次尝试,我更改了<script></script> (我的脚本已经过时了),并修改了此答案<script> ,以实现动态加载内容的目的,并在发布之前验证表单,非常感谢Sthepen Muecke为我提供了一个解决方案并阐明了我的问题...非常感谢。

New Code Script for Load Content Dinamically and Validate Inputs in Modal Bootstrap 3 用于在模式引导程序3中动态加载内容并验证输入的新代码脚本

<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('a.newTourist').click(function () {                
            var url = '@Url.Action("Create", "Tourist", new { id = @Model.id })';
        $(jQuery.noConflict);
        $('#ModalContent').load(url, function (html) {
            var form = $("#Modal-Tourist form");
            $.validator.unobtrusive.parse(form);
            $("#Modal-Tourist").modal('show');
            form.submit(function () {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#Modal-Tourist').modal('hide');
                        var content = '@Url.Action("IndexByEventsTourist", "Tourist", new { id = @Model.id })';
                        $('#eventsDetailsList').load(content);
                    }
                });
                return false;
            });
        });
    });
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM