ASP.NET MVC:模型将null传递给控制器​​

时间:2018-01-19 07:59:52

标签: asp.net asp.net-mvc models controllers

我将数据从一个(模型)表插入到另一个(模型)表中,但它传递的是空值。

以下是控制器的代码:

 public ActionResult PendingBlogs()
    {
        OMSDataContext db = new OMSDataContext();

        var query = from a in db.BlogApprovals
                    select a;
        return View(query);
    }
    [HttpPost]
    public ActionResult PendingBlogs(BlogApproval blogap)
    {
        OMSDataContext db = new OMSDataContext();

        Blog b = new Blog
        {
            BlogTitle = blogap.BlogTitle1,
            BlogContent = blogap.BlogContent1,
            UserName = blogap.UserName1,
            Date = blogap.Date1,
            IsApproved = true
        };
        db.Blogs.InsertOnSubmit(b);
        db.SubmitChanges();

        return RedirectToAction("Index");
    }

这是我的查看代码:

@model IEnumerable<MVCDemo.Models.BlogApproval>
@{
ViewBag.Title = "PendingBlogs";
}

<h2>PendingBlogs</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.BlogTitle1)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.BlogContent1)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.UserName1)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Date1)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.IsApproved1)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.BlogTitle1)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BlogContent1)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UserName1)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Date1)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.IsApproved1)
        </td>
        <td>
            <form asp-controller="Admin" method="post">
                <input type="submit" name="answer" value="RunRegisterdJob" />
            </form>
        </td>
    </tr>
}

</table>

两个模型(Blog和BlogApproval)是models文件夹中的表。 BlogApproval中包含数据,但由于某种原因,它没有从表中返回数据。

我查看过this个帖子,并重新命名了BlogApproval表中的列,以便它们与Blog表中的列不同,但是没有修复它。< / p>

1 个答案:

答案 0 :(得分:0)

您的表单标签不包含任何html输入值,因此不要使用下面的代码

<form asp-controller="Admin" method="post">
        <input type="submit" name="answer" value="RunRegisterdJob" />
</form>

使用以下代码:

<form asp-controller="Admin" method="post">
       <input type="text" name="blogTitle1"/>
       <input type="text" name="blogContent"/>
       <input type="text" name="UserName1"/>
       <input type="submit" name="answer" value="RunRegisterdJob" />
</form>