all my textboxes return null what should I do?

∥☆過路亽.° 提交于 2019-12-11 14:18:29

问题


I have a problem here with regards to elements on my pages returning null even though I have typed something in the textbox. What causes this? I want to make a simple CRUD app with a dashboard for final year.

Here is my view:

@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")
}

Here is my controller action:

[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);
}

回答1:


I think you need to post to the correct ActionName. You use @using (Html.BeginForm()), which will post to the Index of a Controller. But you have Create. So point the form to that.

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



回答2:


Make sure that you have proper viewmodel properties setup first:

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

    public string Name { get; set; }
}

Then point to action name and controller name which handles POST action in BeginForm helper:

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

And finally change parameter name to avoid naming conflict in default model binder, also remove BindAttribute because the POST action has strongly-typed viewmodel class as parameter:

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

    return View(model);
}

Related issue:

POST action passing null ViewModel



来源:https://stackoverflow.com/questions/54385368/all-my-textboxes-return-null-what-should-i-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!