После работы с некоторыми небольшими MVC-приложениями я начал работать с новым приложением MVC с нуля. У меня есть некоторые функции, открывающие PartialView в диалоговом окне jQuery. Этот диалог позволяет пользователю добавлять новую модель. Он сохраняется с помощью кнопки jQuery, поэтому нет submitbutton. Проблема заключается в том, что, когда модель недействительна (например, обязательные поля не заполняются), она выполняет проверкуКнопки диалога jQuery не запускаются ValidationSummary
Краткая история короче; диалог делает то, что ему нужно сделать, для показа моей проверки с помощью диалоговых кнопок
В главном верстки кроме меня есть следующие ссылки
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.8.2.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-ui-1.8.24.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/MicrosoftAjax.debug.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")"></script>
Ниже инициализации DropDownList и кнопки
<label>Area: </label>@Html.DropDownListFor(m => m.SelectedArea.ID, new SelectList(Model.Areas, "ID", "Code", Model.SelectedArea.ID), new { @onchange = "this.form.submit();" }) <input type="button" onclick="openAreaPopup(false)" value="Area toevoegen" />
<div id="addAreaDialog" style="display: none;"></div>
Затем, следуя помещается внутри тегов
<script type="text/javascript">
function openAreaPopup(updateArea) {
if (!updateArea) {
$("#addAreaDialog").dialog({
autoOpen: false,
title: 'Area toevoegen',
width: 500,
height: 'auto',
modal: true,
buttons: {
"Opslaan": function() {
var thisDialog = this;
var form = $('form', this);
if ($(form).validate().form()) {
$.ajax({
type: "POST",
url: "Area/Create",
dataType: "json",
data: JSON.stringify($(form).serialize())
}).success(function (data) {
if (data.success == true) {
$(thisDialog).dialog("close");
window.location.assign(window.location);
}
});
}
},
"Annuleren": function() {
$(this).dialog("close");
}
},
hide: {
effect: "fade",
duration: 250
},
open: function (event, ui) {
$(this).load("/Area/Create");
$(this).load(options.url, function() {
var $jQval = $.validator;
$jQval.unobtrusive.parse($(this));
});
}
});
}
}
</script>
Площадь Модель
public class Area
{
private List<Location> _locations;
public int ID { get; set; }
[Required(ErrorMessage = "This is required")]
public string Code { get; set; }
public string Description { get; set; }
public List<Location> Locations
{
get
{
return _locations ?? (_locations = new List<Location>());
}
set
{
_locations = value;
}
}
}
Контроллер-код:
[HttpGet]
public PartialViewResult Create()
{
return PartialView();
}
//
// POST: /Area/Create
[HttpPost]
[ValidateInput(true)]
public ActionResult Create(FormCollection collection)
{
var model = new Area();
try
{
model.Code = collection["Code"];
model.Description = collection["Description"].TrimEnd('\"');
if (TryValidateModel(model))
{
// Area naar BLL sturen en opslaan
_areaBLL.AddArea(ref model);
return Json(new { success = true });
}
else
{
return PartialView();
}
}
catch
{
return PartialView();
}
}
и, наконец, код Create.cshtml
@model PCLPro.Common.Models.Area
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(false, "De volgende velden zijn niet goed ingevuld")
<fieldset>
<legend>Area</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Code)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Code)
@Html.ValidationMessageFor(model => model.Code)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
</div>
}
Да, у меня есть. Спасибо за быстрый ответ, хотя! Идем упомянуть об этом выше! – Ronald
Не могли бы вы вставить свою модель? –
Хорошо, я думаю, что все необходимое сейчас – Ronald