HiddenFor - Submit loses value the first time

1

Follow the code below:

Index:

@{
    ViewBag.Title = "Home Page";
}

<div class="modal fade" id="minhaModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div id="conteudoModal"></div>
        </div>
    </div>
</div>

<div class="row">
    <button class="btn btn-default" id="myclick">click me</button>
</div>


<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

<script type="text/javascript">

    $("#myclick").click(function () {
        $("#conteudoModal").load("@Url.Action("_minhaPartialView", "Home")", function () {
            $("#minhaModal").modal("show");
        });
    });
</script>

_minhaPartialView:

@model WebApplication1.Models.Modelos

@using (Ajax.BeginForm("MyAction", "Home", new AjaxOptions { HttpMethod = "POST", OnBegin = "OnBegin_Function", OnSuccess = "OnSuccess_Function" }, new { @class = "form-horizontal", role = "form" }))
{
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Título</h4>
    </div>

    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.MyProperty)

    <div class="modal-footer">
        <button type="submit" class="btn btn-success">Salvar</button>
        <button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
    </div>
}

<script type="text/javascript">

 function OnBegin_Function() {
     $('#MyProperty').val(123);
    }

    function OnSuccess_Function() {

    }

</script>

Controller:

[HttpGet]
public ActionResult _minhaPartialView()
{
    var model = new Modelos
    {
        MyProperty = 1
    };

    return PartialView(model);
}

public ActionResult MyAction(Modelos model)
{
    // aqui retorna model.MyProperty = 1 na primeira vez.
    // o certo é retornar valor 123, por exemplo
    return Json(true, JsonRequestBehavior.AllowGet);
}

Problem:

When I submit, the value returns 1 the first time. The second time returns value 123.

UPDATE:

$(function () {
    $('#MyProperty').val(123);  //AQUI FUNCIONA !!!
});

function OnBegin_Function() {  //NÃO FUNCIONA
    $("#MyProperty").val(123);      
}
    
asked by anonymous 05.10.2017 / 01:52

1 answer

1

You are having this problem because you are trying to change a form value after firing the "OnBegin".

According to MSDN :

  

The JavaScript function is called by ASP.NET MVC after the HttpRequest object is instantiated but before it is invoked

Soon, this property is called after the serialization of the form. Taking this into account, it is not possible to change the receipt of the data in your Controller, only in its input. Try changing the values before the serialization of your form .

    
05.10.2017 / 20:17