模型CheckBoxFor属性被发布两次Asp Net MVC 3

时间:2011-08-04 18:32:55

标签: asp.net-mvc-3 c#-4.0

所以我有部分观点......

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<NewsletterUnsubscribe_MVC3v2.Models.IntegraRecord>" %>

<% if (!String.IsNullOrEmpty(Model.ErrorMessage))
   {%>
   <div class="input-validation-error">
    <%:Model.ErrorMessage %>
   </div>
<% }
   else
   {%>

<% using (Html.BeginForm())
{%>
    <%:Html.ValidationSummary(true)%>
    <fieldset>
        <legend>IntegraRecord</legend>
        <div class="editor-field">
                <%:Html.LabelFor(m => m.EmailAddress)%>: <strong><%:Model.EmailAddress%></strong>
        </div>
        <%:Html.HiddenFor(m=>m.EmailAddress) %>
        <div class="editor-field">
                Unsubscribe from Area mailings: <%:Html.CheckBoxFor(m => m.AreaUnsubscribe)%>
        </div>
        <div class="editor-field">
                Unsubscribe from Monthly newsletters: <%:Html.CheckBoxFor(m => m.MonthlyUnsubscribe)%>
        </div>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
<% }
   }%>

当我点击提交并查看发布数据中的内容时,我看到了

EmailAddress:someone@somewhere.co.uk
AreaUnsubscribe:true
AreaUnsubscribe:false
MonthlyUnsubscribe:true
MonthlyUnsubscribe:false

因此,TryUpdateModel返回true但不填充任何字段

这会发布到控制器......

 [HttpPost]
        public ActionResult GetRecord(IntegraRecord model)
        {
            if (TryUpdateModel(model))
            {
                try
                {
                    BusinessLayer.UpdateEmailAddress(model);
                }
                catch (ArgumentException)
                {
                    return View("Error", ViewBag.Message = "Could Not Update Email Address.");
                }
            }
            return PartialView("GetRecord", model);
        }

任何帮助都非常感激......


更新:按照下面的说明(谢谢!)

我没有使用自定义模型绑定器,所以我想我也错过了其他一些约定...

这是我的模特......

public class IntegraRecord
    {
        private const string EmailRegex = @"[snip]";

        [Required(ErrorMessage = "Email Address is required")]
        [RegularExpression(EmailRegex, ErrorMessage = "This does not appear to be an email address")]
        public string EmailAddress;

        public bool AreaUnsubscribe;
        public bool MonthlyUnsubscribe;

        public string ErrorMessage;

        public IntegraRecord()
        {
        }

        public IntegraRecord(string email, bool area, bool monthly)
        {
            EmailAddress = email;
            AreaUnsubscribe = area;
            MonthlyUnsubscribe = monthly;
        }
    }

1 个答案:

答案 0 :(得分:1)

这就是MVC处理复选框的方式:asp.net mvc: why is Html.CheckBox generating an additional hidden input(以及许多其他地方) 问题出在服务器端(默认模型绑定器知道这一点并且没有问题)。你在使用自定义模型绑定器吗?