Я использую приложение Mvc 4.
У меня есть partialView, который находится внутри диалогового окна пользовательского интерфейса Jquery. Я пытаюсь добавить проверки на стороне клиента при нажатии переключателя, но когда я добавляю $("#FormID").validate(); в моем сценарии происходит то, что проверки на стороне сервера не работают. Ниже мой код
Частичный вид
@using (Html.BeginForm("_EditDealPartial", "RDeals", FormMethod.Post, new { onSubmit = "return Check_Date();", id = "EditDealForm", @class = "bootstrap-frm" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.UserId)
@Html.HiddenFor(m => m.CreateDate)
@Html.HiddenFor(m => m.CodeGenerated)
<table>
<tr>
<td style="white-space: nowrap">@Html.LabelFor(m => m.Description)</td>
<td>@Html.TextBoxFor(m => m.Description)</td>
</tr>
<tr>
<td colspan="4">
@Html.RadioButtonFor(m => m.Type, "P", new { id = "PointBased" })
@Html.Label("PointBased", "Point Based (E.g. Collect xyz Points to earn a FREE meal or $ )")
</td>
</tr>
<tr id="Point1" style="display: none">
<td>
@Html.Label("Collect Points:")
</td>
<td>
@Html.TextBoxFor(m => m.Buy, new { id = "PBuy", style = "width:50px;" })
</td>
<td style="white-space: nowrap">
@Html.RadioButtonFor(m => m.PointEarnType, 1, new { id = "PointEarnType1" })@Html.Label("PointEarnType1", "Earn $(dollars) towards meal:")
</td>
<td>
@Html.TextBoxFor(m => m.Free, new { id = "PFreeDollars", style = "width:50px;" })
</td>
</tr>
<tr id="Point2" style="display: none">
<td> </td>
<td> </td>
<td style="white-space: nowrap">
@Html.RadioButtonFor(m => m.PointEarnType, 2, new { id = "PointEarnType2" })@Html.Label("PointEarnType2", "Earn Free meal:")
@Html.DropDownListFor(m => m.Free, ViewBag.FreeList as SelectList, " Select ", new { id = "PFreeMeal" })
</td>
<td>
@Html.TextBoxFor(m => m.PointEarnMealText, new { placeholder = "eg:Burger or Fries" })
</td>
</tr>
<tr>
<td colspan="4">
@Html.RadioButtonFor(m => m.Type, "V", new { id = "ValueBased", @checked = true })
@Html.Label("ValueBased", "Volume Based (E.g. Buy 5 to Earn 1 FREE meal)")
</td>
</tr>
<tr id="Volume1">
<td>@Html.LabelFor(m => m.Buy)</td>
<td>@Html.DropDownListFor(m => m.Buy, ViewBag.BuyList as SelectList, "Select")</td>
<td style="white-space: nowrap">@Html.LabelFor(m => m.Free)</td>
<td colspan="2">@Html.DropDownListFor(m => m.Free, ViewBag.FreeList as SelectList, "Select")</td>
</tr>
<tr id="Volume2">
<td> </td>
<td>
@Html.TextBoxFor(m => m.VolumeBuyText, new { placeholder = "Eg:Burger or Fries" })
</td>
<td> </td>
<td>
@Html.TextBoxFor(m => m.VolumeEarnText, new { placeholder = "Eg:Burger or Fries" })
</td>
</tr>
<tr>
<td style="white-space: nowrap">@Html.LabelFor(m => m.ExpiryDate)</td>
<td>@Html.EditorFor(m => m.ExpiryDate)</td>
</tr>
</table>
}
Моя модель
public class R_DealsMetaData
{
public int ID { get; set; }
public int UserId { get; set; }
[Required(ErrorMessage="Please Enter Description")]
[Display(Name="Promotion Name:")]
public string Description { get; set; }
[Required(ErrorMessage = "Please select one Option")]
[Display(Name = "Deal Buy:")]
public int Buy { get; set; }
[Required(ErrorMessage = "Please select one Option")]
[Display(Name = "Deal Free:")]
public int Free { get; set; }
public Nullable<bool> Status { get; set; }
public string Type { get; set; }
[DataType(DataType.Date)]
public System.DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[Required(ErrorMessage = "Please select Expiry Date")]
[Display(Name = "Promotion Expiry Date:")]
public System.DateTime ExpiryDate { get; set; }
public Nullable<int> PointEarnType { get; set; }
public string PointEarnMealText { get; set; }
public string VolumeBuyText { get; set; }
public string VolumeEarnText { get; set; }
}
Код jQuery внутри PartialView
$(document).ready(function () {
$('#EditDealForm').validate();
$("#PBuy").attr('disabled', true);
$("#PointEarnType").attr('disabled', true);
$("#PFreeDollars").attr('disabled', true);
$("#PFreeMeal").attr('disabled', true);
$("#VolumeBuyText").rules('add', { required: true, messages: { required: "Please enter free meal name" } });
$("#VolumeEarnText").rules('add', { required: true, messages: { required: "Please enter free meal name" } });
$("input:radio[name=Type]").change(function () {
if (this.value == "P") {
$("#Point1").show();
$("#Point2").show();
$("#Volume1").hide();
$("#Volume2").hide();
$("#Buy").attr('disabled', true);
$("#Free").attr('disabled', true);
$("#PBuy").attr('disabled', false);
$("#PointEarnType").attr('disabled', false);
$("#PFreeDollars").attr('disabled', false);
$("#PFreeMeal").attr('disabled', false);
$("#PBuy").val("");
$("#PFreeDollars").val("");
$("#VolumeBuyText").rules('remove');
$("#VolumeEarnText").rules('remove');
$("#PointEarnType1").rules('add', { required: true, messages: { required: "Please select one option" } });
$("#PointEarnType2").rules('add', { required: true, messages: { required: "Please select one option" } });
}
else if (this.value == "V") {
$("#Point1").hide();
$("#Point2").hide();
$("#Volume1").show();
$("#Volume2").show();
$("#PBuy").attr('disabled', true);
$("#PointEarnType").attr('disabled', true);
$("#PFreeDollars").attr('disabled', true);
$("#PFreeMeal").attr('disabled', true);
$("#Buy").attr('disabled', false);
$("#Free").attr('disabled', false);
$("#VolumeBuyText").rules('add', { required: true, messages: { required: "Please enter free meal name" } });
$("#VolumeEarnText").rules('add', { required: true, messages: { required: "Please enter free meal name" } });
$("#PointEarnType1").rules('remove');
$("#PointEarnType2").rules('remove');
}
});
$("input:radio[name=PointEarnType]").change(function () {
if (this.value == "1") {
$("#PFreeDollars").attr("disabled", false);
$("#PFreeMeal").attr("disabled", true);
$("#PointEarnMealText").attr("disabled", true);
$("#PointEarnMealText").rules('remove');
$("#PFreeDollars").addClass("input-validation-error");
$("#PointEarnMealText").removeClass("input-validation-error");
$("#PFreeMeal").removeClass("input-validation-error");
}
else if (this.value == "2") {
$("#PFreeDollars").attr("disabled", true);
$("#PFreeDollars").removeClass("input-validation-error");
$("#PFreeMeal").attr("disabled", false);
$("#PointEarnMealText").attr("disabled", false);
$("#PointEarnMealText").rules('add', { required: true, messages: { required: "Please enter free meal name" } });
$("#PointEarnMealText").addClass("input-validation-error");
$("#PFreeMeal").addClass("input-validation-error");
}
});
Когда я проверяю проверку форм
var form = $("#EditDealForm");
$.validator.unobtrusive.parse(form);
if (!$(form).valid())
return false;
else
$(this).empty().dialog('close');
Он возвращает false только для правил проверки на стороне клиента, которые я добавил в скрипт partialView, но проверки на стороне сервера возвращают true, диалоговое окно закрывается. Не знаю, где я ошибаюсь
Пожалуйста, помогите мне. Спасибо!
VolumeBuyText
,VolumeEarnText
и т. д.? - person   schedule 12.11.2014Buy
,Description
,Free
и т. д.) - person Kumar   schedule 12.11.2014ModelState
на наличие ошибок проверки в методе POST? - person   schedule 12.11.2014ModelState.IsValid
возвращаетfalse
, то есть ошибки проверки, поэтому он работает. Не уверен, что вы спрашиваете или ожидаете, что произойдет. - person   schedule 12.11.2014$.validator.unobtrusive.parse(form);
вы должны добавитьform.data('validator', null);
, чтобы валидатор очищался, и тогда форма могла быть правильно проанализирована - person   schedule 12.11.2014