我正在尝试检查typeId&的组合supplementId已存在于我的数据库中。所以我已经为我的supplementId添加了一个remoteattribute来执行此操作。我的问题是验证应该在更改下拉列表时触发。我有点用ddl onchange上的javascript修复了这个客户端。但现在我无法发布我的表格。当我单击该按钮时,它会聚焦最后一个下拉列表但不显示任何错误,并且控制器中的Post方法不会被触发。如果我在chrome控制台中执行form.submit(),则会调用该方法,但会忽略验证。以前有人遇到过这个问题吗?
BTW此代码被清除到最低限度,因此可能缺少标签,错误消息等, 这些不应该是问题。
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SupplementTypeClass>" %>
<script src="<%: Url.Content("~/Scripts/jquery-1.5.1.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"
type="text/javascript"></script>
<% using (Html.BeginForm("AddEditSupplementType", "Supplement"))
{ %>
<%: Html.ValidationSummary(true)%>
<fieldset>
<legend>
Add type
</legend>
<div class="editor-content">
<div class="editor-label">
<%: Html.LabelFor(model => model.SupplementId)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.SupplementId, new SelectList(ViewBag.Supplements, "SupplementId", "Name", Model.SupplementId), "Select supplement", new { onchange = "$('#ddl').removeData('previousValue');$('#ddl').valid();" })%>
<%: Html.ValidationMessageFor(model => model.SupplementId)%>
</div>
</div>
<div class="editor-content">
<div class="editor-label">
<%: Html.LabelFor(model => model.TypeId)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.TypeId, new SelectList(ViewBag.Types, "TypeId", "Name", Model.TypeId), "Select type", new { id ="ddl" })%>
<%: Html.ValidationMessageFor(model => model.TypeId)%>
</div>
</div>
<div class="editor-buttons">
<input type="submit" value="Save" />
</div>
</fieldset>
<% } %>
[HttpPost]
public ActionResult AddEditSupplementType(SupplementTypeClass sup)
{
if (ModelState.IsValid)
{
//code to insert to DB
}
return RedirectToAction("FicheAddEditSupplementType", new { supplementTypeId = sup.supplementTypeId});
}
public class SupplementTypeClass
{
#region Members
public int SupplementId { get; set; }
[RemoteAttribute("SupplementTypeCheck", "Supplement", AdditionalFields = "SupplementId")]
public int TypeId { get; set; }
#endregion
}
答案 0 :(得分:1)
Remote属性默认使用GET方法进行Ajax调用,而不是POST。
让您熟悉模型中的POST方法
[RemoteAttribute("SupplementTypeCheck", "Supplement", AdditionalFields = "SupplementId", HttpMethod="POST")]