MVC远程属性 - 提交问题

时间:2012-02-20 12:49:23

标签: asp.net-mvc-3

我正在尝试检查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
}

1 个答案:

答案 0 :(得分:1)

Remote属性默认使用GET方法进行Ajax调用,而不是POST。

让您熟悉模型中的POST方法

[RemoteAttribute("SupplementTypeCheck", "Supplement", AdditionalFields = "SupplementId", HttpMethod="POST")]