【问题标题】:Modelbinding brakes on after adding html5 attributes添加 html5 属性后模型绑定停止
【发布时间】:2011-10-26 11:50:42
【问题描述】:

我有一个视图,它使用 TextBoxFor 辅助方法来编辑模型。像这样:

<div class="editor-field">
                <%:Html.TextBoxFor(model => model.Property, new { @class = "mybox" })%>
                <%: Html.ValidationMessageFor(model => model.Property)%>
</div>

所以,Modelbinder 工作正常,我可以编辑和保存我的模型。

当我像这样添加 html5 属性“类型”和“步骤”时

<div class="editor-field">
                <%:Html.TextBoxFor(model => model.Property, new { @class = "mybox",@type = "number", @step = "1" })%>
                <%: Html.ValidationMessageFor(model => model.Property)%>
</div>

我看到漂亮的数字控件而不是文本框,但是模型绑定会刹车,每当我更改我的属性时,我都会在我的模型中收到 0。提交时的属性。

我的代码有什么问题?

这是我的简单模型

public class Model
    {

        [DisplayName("Property")]
        public int Property
        {
            get;
            set;
        }           
    }

内森,我对这个问题的解释在这里并不准确。这里Ajax Form breaks after adding html5 attributes in Chrome/Safari 是更好的描述和解决方法。

【问题讨论】:

    标签: asp.net-mvc-2 html model-binding


    【解决方案1】:

    试试这个:

    http://deanhume.com/Home/BlogPost/asp-net-mvc-html5-toolkit/29

    根据您的代码,这对我有用:

    控制器:

    public class IndexController : Controller
    {
    
        public ActionResult Index()
        {
            return View();
        }
    
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(Model model)
        {
            return Content(model.Property.ToString());
        }
    
    }
    

    型号:

    public class Model
    {
        [DisplayName( "Property" )]
        public int Property
        {
            get;
            set;
        }
    }
    

    查看:

    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<BindTest.Models.Model>" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
        <head runat="server">
            <title>Index</title>
        </head>
        <body>
        <%using( Html.BeginForm( "index", "index" ) ){ %>
            <div class="editor-field">
                <%=Html.TextBoxFor(model => model.Property, new {@class = "mybox", @type = "number", @step = "1"})%>
                <%=Html.ValidationMessageFor(model => model.Property)%>
            </div>
    
            <button type="submit" value="click Me">Click Me</button>
    
        <% } %>
        </body>
    </html>
    

    当我点击提交按钮时,在我的数字输入控件中选择的数字被控制器接收并输出到浏览器。

    我们需要查看更多代码才能更有帮助。

    【讨论】:

    • 谢谢,但我想知道我的示例有什么问题。并且第三方库并不是解决这个问题的最佳方式。
    • 我之前已经成功使用过,认为他的源代码中的某些内容可能会对您有所帮助。也就是说,我刚刚尝试了您的示例,它对我来说效果很好。你能提供你的控制器代码吗?
    • Nathan,感谢您的帮助 - 我已经按照您的方式进行了尝试,发现我遇到的问题仅发生在 Chrome/Safari 浏览器上。在 IE/Firedox 中没关系。我唯一改变的是表单——在我的例子中是 Ajax
    • Nathan,所以当我将 AjaxForm 更改为 HtmlForm 时,Chrome/Safari 中的问题消失了。有什么想法吗?
    • 别想了,不。当我将上面发布的示例从 Html.BeginForm 更改为 Ajax.BeginForm 时,它仍然可以正常工作。
    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多