使用Html.BeginForm呈现表单时不显示TextBox

本文关键字:显示 TextBox 表单 Html BeginForm 使用 | 更新日期: 2023-09-27 18:28:06

我刚刚开始学习ASP MVC 4,我正在做一个基本的练习,这是一个图书托管网站。

我目前正在开发一个控制器,用于将新书添加到存储库中。适当操作的视图被强类型化为Book类作为其模型。Book是一个非常简单的模型,由标题、作者等组成。

我的AddBook控制器目前看起来是这样的:(我还没有在POST上实现任何数据库插入逻辑)

public class AddBookController : Controller
{
    [HttpGet]
    public ActionResult AddBook()
    {
        return View();
    }
    [HttpPost]
    public ActionResult AddBook(Book book)
    {
        return View();
    }
}

我的观点也很简单:


@model Bookshare.Models.Book
@{
    ViewBag.Title = "AddBook";
}

Add a new book

@using (Html.BeginForm()) { Html.TextBoxFor(model => model.Title); Html.TextBoxFor(model => model.Author); Html.TextBoxFor(model => model.PublishingCompany); Html.TextBoxFor(model => model.ReleaseYear); Html.TextBoxFor(model => model.Summary); }

然而,当我调用此操作时,我所能看到的只是表单的"添加新书"标题和提交按钮。没有任何文本框。如果我使用普通的旧Html.TextBox语法,也会发生这种情况。查看页面的源代码只会显示一个空的表单标记。

我在这里做错了什么?

使用Html.BeginForm呈现表单时不显示TextBox

使用Html Helper的方式是错误的。TextBoxFor方法不是像Html.TextBoxFor(...);那样调用的void方法。它返回要在页面上写入的MvcHtmlString对象。因此,您使用它如下:

@Html.TextBoxFor(model => model.Title)   

上述代码中的@相当于经典asp中的Response.Write

所以,你的表单最简单的方式应该是这样的:

@using (Html.BeginForm())
{
    @Html.TextBoxFor(model => model.Title)
    @Html.TextBoxFor(model => model.Author)
    @Html.TextBoxFor(model => model.PublishingCompany)
    @Html.TextBoxFor(model => model.ReleaseYear)
    @Html.TextBoxFor(model => model.Summary)
}

但是,这将使所有的TextBox挨着显示,没有标签,也没有验证消息的占位符。将视图中的每个TextBox替换为以下内容,以便在页面上正确设置它们的格式,并添加标签和验证消息占位符。

<div class="editor-label">
    @Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Title)
    @Html.ValidationMessageFor(model => model.Title)
</div>

EditorFor将呈现为字符串属性的TextBox。

事实证明,要获得正确的表单,您只需要以下内容。创建方法的控制器可以是这样的:

    public ActionResult Create()
    {
        return View();
    }

我的工作观点是这样的,你的领域当然会略有不同:

  @using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Book</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Author)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Author)
            @Html.ValidationMessageFor(model => model.Author)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

有了这个,我可以在浏览器中看到呈现的表单。