开发者

Unexpected side effect of HtmlHelpers in ASP.NET

I have an ASP.NET MVC form for adding a module to a site. The view has a strongly typed ViewModel with the properties "Name" and "Content". On this form I have a sub-form for adding a section to the module. The sub-form has fields labeled "Name" and "Content" as they apply to the section object. However, unfortunately for me, the built-in HTML helper functions appear to be autobinding these fields to the matching property values on the view model, even though they are intended to apply to a completely different object.

Example classes:

public class Module 
{
    public string Name {get;set;}
    public string Content {get;set;}
    // ...
}

public class Section 
{
    public string Name {get;set;}
    public string Content {get;set;}
    // ...
}

Form:

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

<!-- rest of page here -->

<%using (var form = Html.BeginForm("AddSection", "Modules")){%>

    <ul class="form">
        <li>
            <label for="Number">Section Number:</label>
            <%=Html.TextBox("Number", null, new { size=5, maxlength=5 })%>
            <%=Html.ValidationMessage("Number")%>
        </li>
        <li>
            <label for="Name">Section Name:</label>
            <%=Html.TextBox("Name")%>
            <%=Html.ValidationMessage("Name")%>
        </li>        
        <li>
            <div style="width: 75%;">
                <label for="Content">Section开发者_开发知识库 Content: (<a href="http://textile.thresholdstate.com" target="_blank">formatting help</a>)</label>
                <%=Html.TextArea("Content", null, new { @class = "text-entry" })%>
                <%=Html.ValidationMessage("Content")%>
            </div>
        </li>
        <li>
            <div style="width: 75%;">
                <label>Content Preview: (<a href="#" onclick="togglePreviewPane(true); return false;">Show / Hide</a>)</label>
                <div id="PreviewBox" class="black-border text-entry">&nbsp;</div>
            </div>
        </li>
    </ul>

    <input type="hidden" id="ModuleID" name="ModuleID" value="<%=Model.ID%>" />
    <input type="submit" id="SubmitButton" name="SubmitButton" value="Add Section" />
<%}%>

I would expect that the Name and Content inputs start out blank, but the html helpers seem to be prebinding to the page's view model without my direction. How can I stop this...


try to put <%=Html.TextBox("Name",string.Empty)%> to force the textbox to be blank

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜