简体   繁体   中英

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?

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

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 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.

New Code Script for Load Content Dinamically and Validate Inputs in Modal Bootstrap 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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