Problems with Ajax.BeginForm Razor MVC4

4

Good morning. I had previously posted a problem with a form , but I'm still I can conclude this module. The problem is that when I open this Formulario Ajax (which opens in a dialog and the div of it is out of any other form - is within layout ), I add the data and doing the submit happens more than 1 time for the action of controller (up to 10 times), as if you had pressed the submit button many times, and never delete the data of textbox .

<div id='Div-AB-Email' style="display: none">
    <div id='Div-Email'></div>
</div>

JS:

function abrirFormEmail() {
    Preloader();
    preloaderBusquedas("Div-Email");

    $("#Div-AB-Email").dialog({
        autoOpen: true,
        open: function (event, ui) {
            $("#Div-Email").load("/EmailPersona/Create");
            $("#Mail").val("");
            $("#Observaciones").val("");

        },
        focus: function (event, ui) { $("#Mail").focus(); },
        show: {
            effect: "blind",
            duration: 500,
        },
        hide: {
            effect: "blind",
            duration: 500
        },
        width: 1036,
        height: 400,
        title: "Email de contacto ",
        closeOnEscape: true,



    });

    PreloaderOff();
}

C #:

 public class EmailPersonaController : BaseController
{



    public PartialViewResult Create()
    {
        return PartialView();
    }



    [HttpPost]
    public PartialViewResult Create(EmailPersonaModel model)
    {
        if (model == null)
            return PartialView();

        if (model.IdPersona == 0)
        {

            model.IdPersona = ConsultaIdPersona();
            ModelState.Remove("IdPersona");
        }


        try
        {
            if (ModelState.IsValid)
            {

                if (model.Nuevo())
                {
                    model.grabado = true;
                    ListItemsCarga().Add(model);
                    var modelnull = new EmailPersonaModel();
                    return PartialView(modelnull);
                }

                else
                {
                    return PartialView(model);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(model.Mail))
                    TempData["ErrorEmail"] = "Debe escribir el mail que desea agregar a la lista";
            }
            return PartialView(model);
        }
        catch (Exception e)
        {
            if (e.Message == "ERROR: 23505: llave duplicada viola restricción de unicidad «uq_email_per»")
            {

               TempData["ErrorEmail"] = "El Mail que quiere cargar pertenece a otra persona";
            }

            return PartialView();
        }
    }
}

Razor:

@model QBOWEB3.Models.EmailPersonaModel
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
@{
    ViewBag.Title = "Create";
}

@using (Ajax.BeginForm("Create", "EmailPersona",
new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
   UpdateTargetId = "Div-Email"


}))  
{

    <fieldset>


            <h3>Email De Contacto</h3>
            <span>@ViewBag.Afiliado</span>
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)


            <legend>EmailPersonaModel</legend>



        <div id="contenidoEmail">

            <table class="TableCampsEdicion">

                <tr>

                    <td class="tdLabel">
                        @Html.LabelFor(model => model.Mail)
                    </td>

                    <td class="tdTextBox">
                        @Html.EditorFor(model => model.Mail)

                    </td>

                    <td class="tdLabel">


                        @Html.LabelFor(model => model.Observaciones)
                    </td>

                    <td class="tdTextBox">
                        @Html.EditorFor(model => model.Observaciones)

                    </td>

                    @Html.EditorFor(model => model.IdPersona)

                    <td class="tdTextBox">
                        <input type="submit" value="Agregar" class="botonAzulMediano" style="width: 95px; margin-left: 10px;" />

                    </td>
                </tr>
                <tr>
                    <td class="tdTextBox" colspan="5">
                        @Html.ValidationMessageFor(model => model.Mail)
                        @Html.ValidationMessageFor(model => model.Observaciones)
                    </td>
                </tr>
            </table>


        @*    <div id="itemsEmail">@Html.Action("Index")</div>*@

            @if (@TempData["ErrorEmail"] != null && @TempData["ErrorEmail"].ToString() != "")
            {
                <script>
                    $(function () {

                        mensaje("@TempData["ErrorEmail"]");


                    });
                </script>
            }
            @if (Model != null && Model.grabado)
            {
                <script>
                    $(function () {

                        $("#Mail").val("");
                        $("#Observaciones").val("");



                    });

                </script>



            }

            <script>
                $(function () {
                    $("#Mail").focus();
                    Enter_por_Tab();
                    PreloaderOff();


                })


            </script>
        </div>
    </fieldset>
}
    
asked by Ariel Octavio D'Alfeo 03.02.2016 в 15:10
source

1 answer

4

As I suggested in the comments, you could try changing the Ajax.BeginForm to an invocation that uses jquery $ .ajax.

To send the form you could use the .serialize () from jquery about form

Web API With AJAX: Submit Form Data After Serialization

The example shows that it uses data: $('#form1').serialize(), to send the data of form to the action of the controller

$("#Save").click(function () {
        $.ajax({
            url: '@Url.Action("NombreAction")',
            type: 'POST',
            dataType: 'json',
            data: $('#form1').serialize(),
            success: function (data, textStatus, xhr) {
                console.log(data);
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log(textStatus);
            }
        });
});

But do not defend an Ajax or Html BeginForm in the partialview, but use the form tag as html .

> > In the create action of the controller, what should I return?

The return depends, some return a json or a HttpStatusCodeResult indicating a Ok of http But it could also be a void or a simple value like string or bool

    
answered by 03.02.2016 / 16:12
source