如何在创建视图中显示最近插入的ID

时间:2014-07-31 10:16:55

标签: asp.net-mvc html-helper

我正在使用MVC创建一个应用程序,我有一个名为Week的实体。在创建页面中,我想显示最近创建的一周的ID,以帮助用户避免输入错误的周数。例如,当我创建第3周时,我希望它显示"最后一周是第2周和第34周;在输入框上方或沿着这些线的东西。我尝试使用以下代码,但它似乎不起作用,我不知道为什么。

Create中的

WeekController

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="WeekID,YearID")] Week week)
    {
        try
        {
            if (ModelState.IsValid)
            {
                db.Weeks.Add(week);
                db.SaveChanges();

                int latestKey = week.WeekID;
                ViewBag.latestKey = latestKey;

                return RedirectToAction("Index", "Year");
            }
        }
        catch (DataException /* dex */)
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Maybe this week already exists. If not, try again, and if the problem persists see your system administrator.");
        }

        ViewBag.YearID = new SelectList(db.Years, "YearID", "YearID", week.YearID);
        return View(week);
    }

周视图中的Create页面:

@model Utility3.Models.Week

@{
    ViewBag.Title = "Create";
}

<h1>Add Week</h1>


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

    <div class="form-horizontal">
        @*<h4>Week</h4>*@
        <hr />
        @Html.ValidationSummary(true)


        <p>Last week made was: @ViewBag.latestKey</p>

        <div class="form-group">
            @Html.Label("Week number", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.WeekID)
                @Html.ValidationMessageFor(model => model.WeekID)
            </div>
        </div>

        <div class="form-group">
        @Html.Label("Year", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("YearID", String.Empty)
            @Html.ValidationMessageFor(model => model.YearID)
        </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 Year List", "Index", "Year")
</div>

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

我尝试保存最后创建的一周的ID,并将其传递给ViewBag,但它不起作用。

任何人都能帮助我吗?

1 个答案:

答案 0 :(得分:0)

答案很简单,你已经将Week Model传递回了你的视图,所以不要使用Viewbag,只需像这样使用Model.WeekID:

<p>Last week made was: @Model.WeekID</p>

享受!