0

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 Page rendering correctly Modal with Error from my Controller (in new page not in your main stage) Update Succesfuly but not update my div in my page correctly

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>
  • you need to add `method:POST` to ajax calls, if you are trying to make a POST request. – rrk Aug 17 '15 at 05:49
  • The CRUD operation work correctly but update the div inside from the main view don't and the validation error neither, I put `type:'POST'` in the ajax calls and don't show changes.... @RejithRKrishnan – Der Schwarze König Aug 17 '15 at 05:59
  • your submit passes trough your ".valid()" function? – Julo0sS Aug 17 '15 at 06:07
  • Indeed, in my controller code @Julo0sS – Der Schwarze König Aug 17 '15 at 06:10
  • question not really clear to me, you say then that your form is submitted, your code (insert) works properly, but once your form is submitted, your "parent" page gets updated with bad data? if it's the case then your error comes certainly from your success part in your ajax call. You may try your code without a form but with event handlers – Julo0sS Aug 17 '15 at 06:15
  • Sorry for the explanation in the post; my parent page doesn't update correctly and my modal (insert page) don't show the error validation, I post several images to explain a more details the issue... @Julo0sS – Der Schwarze König Aug 17 '15 at 06:19
  • Not really clear what your wanting to do. Your POST method contains `RedirectToAction()` which is pointless - your making an ajax call and ajax does not redirect - that needs to be a `return PartialVew();` Then if `ModelState` is not valid you do return a partial view (I assume that's the form) but in the success callback, you **hide** the modal and display the form in another element –  Aug 17 '15 at 06:21
  • @StephenMuecke The `RedirectToAction()` result is a list to fill my parents page or other partial view with a `{Html.RenderAction("IndexByEventsTourist", "Tourist", new { id = Model.id });}` , you asume from the form is correctly, I hide the the modal and update with the RedirectToAction() with retrieve the list to update the
    element in my parent page but doesn't
    – Der Schwarze König Aug 17 '15 at 06:29
  • `RedirectToAction()` is pointless as I noted - ajax calls do not redirect! It should be a `return PartialView();` And again as I noted, if your returning the form then how do you expect it to display in the modal when you have hidden it (and just put the form inside another element - which no doubt does not have the relevant css selectors) –  Aug 17 '15 at 06:33
  • @StephenMuecke I update the question, please see the update and tell me what is wrong in that logic and thanks again for your patience in this topic... – Der Schwarze König Aug 17 '15 at 06:36
  • 1
    It appears you dynamically loading the content of the model which means that no client side validation will be triggered. You need to re-parse the validator after adding the dynamic content as per [this answer](http://stackoverflow.com/questions/31768946/required-field-validations-not-working-in-jquery-popup-mvc-4/31769058#31769058). Then `$(this).valid()` will return `false` if the form is not valid and so it will not submit. –  Aug 17 '15 at 06:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/87137/discussion-between-kingve-and-stephen-muecke). – Der Schwarze König Aug 17 '15 at 07:22

1 Answers1

0

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>
Community
  • 1
  • 1