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">×</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);
}