Я хочу установить выбранный элемент DDL с элементом, вставленным во всплывающую страницу. Используется пример сценария здесь - http://www.advancesharp.com/blog/1126/search-sort-paging-insert-update-and-delete-with-asp-net-mvc-and-bootstrap-modal-popup-part-2ASP.NET MVC5, JSON, popup partialView - выбрано DropDownList
в JsonResult я вижу вставленное значение (проверка в режиме отладки с точки останова), но нужна помощь с установкой этого значения, выбранные в DDL на главной странице.
public ActionResult WorkPlaces(int id = 0)
{
var workPlace = new Work();
return PartialView("WorkPlaces", workPlace);
}
[HttpPost]
public JsonResult WorkPlaces(Work work)
{
if (ModelState.IsValid)
{
db.Works.Add(work);
db.SaveChanges();
return Json(new { success = true });
}
return Json(work, JsonRequestBehavior.AllowGet);
}
Модель классы
public class Person
{
public int Id { get; set; }
[Display(Name = "Person Name")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Name is required")]
public string Name { get; set; }
public Nullable<int> WorkId { get; set; }
public virtual Work Work { get; set; }
}
public class Work
{
public int Id { get; set; }
[Display(Name = "Work place")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Name is required")]
public string workPlace { get; set; }
}
Главная
@model testAppAuth.Models.Person
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Person</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.WorkId, "WorkId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("WorkId", null, htmlAttributes: new {@class = "form-control"})
@Html.ValidationMessageFor(model => model.WorkId, "", new {@class = "text-danger"})
<a class="btn btn-success" data-modal="" href="/Person/WorkPlaces" id="btnCreate">
<span class="glyphicon glyphicon-plus"></span>
</a>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
@section scripts{
@Scripts.Render("~/Scripts/Appjs/WorkPlace.js")
}
Всплывающее страница
@model testAppAuth.Models.Work
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Add new workplace</h3>
</div>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Work place</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.workPlace, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.workPlace, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.workPlace, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="modal-footer">
<span id="progress" class="text-center" style="display: none;">
<img src="/images/wait.gif" alt="wiat" />
Wait..
</span>
<input class="btn btn-primary" type="submit" value="Save" />
<button class="btn btn-warning" data-dismiss="modal">Close</button>
</div>
}
<script>
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
</script>
сценарий для всплывающего меню
$(function() {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function() {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function() {
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
location.reload();
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
Кроме того, с этим скриптом даже я установил атрибут [Обязательный] в классах модели, он закрывается, если я нажимаю кнопку закрытия без полей заполнения. Как заставить его не закрываться?