【问题标题】:all my textboxes return null what should I do?我所有的文本框都返回 null 我该怎么办?
【发布时间】:2019-06-20 11:23:05
【问题描述】:

我在页面上的元素返回null 时遇到问题,即使我在文本框中输入了一些内容。这是什么原因造成的?我想为最后一年制作一个带有仪表板的简单 CRUD 应用程序。

这是我的看法:

@model WebApplication1.Models.Category

@{
    ViewBag.Title = "Create Category";
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class 
        ="control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.Name, new { htmlAttributes = 
            new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { 
            @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
} 

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

这是我的控制器操作:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name")] Category category)
{
    if (ModelState.IsValid)
    {
        db.Categories.Add(category);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(category);
}

【问题讨论】:

    标签: asp.net razor model-view-controller null html.textboxfor


    【解决方案1】:

    我认为您需要发布到正确的 ActionName。您使用@using (Html.BeginForm()),它将发布到控制器的索引。但是你有Create。所以把表格指向那个。

    @using (Html.BeginForm("Create", "Home", FormMethod.Post))
    

    【讨论】:

      【解决方案2】:

      确保您首先设置了正确的视图模型属性:

      public class Category
      {
          public int ID { get; set; }
      
          public string Name { get; set; }
      }
      

      然后在BeginForm helper中指向处理POST动作的动作名称和控制器名称:

      @* assumed the controller name is 'CategoryController' *@
      @using (Html.BeginForm("Create", "Category", FormMethod.Post))
      {
          // form contents
      }
      

      最后更改参数名称以避免默认模型绑定器中的命名冲突,同时删除BindAttribute,因为 POST 操作具有强类型视图模型类作为参数:

      [HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult Create(Category model)
      {
          if (ModelState.IsValid)
          {
              db.Categories.Add(model);
              db.SaveChanges();
              return RedirectToAction("Index");
          }
      
          return View(model);
      }
      

      相关问题:

      POST action passing null ViewModel

      【讨论】:

      • 大家好,非常感谢您的帮助,事实证明我为控制器使用了错误的命名空间(因为我复制粘贴了页面)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多