将数据从控制器传递到视图ASP.NET

本文关键字:视图 ASP NET 数据 控制器 | 更新日期: 2023-09-27 17:50:49

我有一个问题,将变量从控制器传递到视图。我创建了一个actionresult,允许用户向餐厅菜单添加餐点。我需要一个html操作链接中的menuID来访问菜单详细信息页面。但是当我运行页面ViewData["MenuID"]返回为空,即使menuID在控制器动作结果中有一个值。是否有其他方法将数据从控制器发送到视图?

创建操作结果

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(MealviewModel model, int? menuID)
        {
            if (menuID == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            else
            {
                ViewData["MenuID"] = menuID;
                if (ModelState.IsValid)
                {
                    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                    var currentUser = manager.FindById(User.Identity.GetUserId());

                    var currentrestaurant = (from r in db.Restaurants
                                             where r.UserID == currentUser.Id
                                             select r).First<Restaurant>().id;
                    var currentmenu = (from m in db.Menus
                                       where m.Restaurantid == currentrestaurant
                                       select m).First<Menu>().Id;
                    var meal = new Meal() { Name = model.Name, Description = model.Description, Price = model.Price, MenuID = menuID, Catergory = model.Catergory };
                    db.Meals.Add(meal);
                    db.SaveChanges();
                    return RedirectToAction("Create", new { MenudID = menuID });
                }
            }
            return View();
        }

创建CSHTML页面

@model BiteWebsite.Models.MealviewModel
@using BiteWebsite.Models;
@{
    ViewBag.Title = "Add Items to Your Menu";
}
<h2>Add Items to Your Menu</h2>
@using (Html.BeginForm())
{
    var ID = ViewData["MenuID"];
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true)
        <div class="form-group">
            @Html.LabelFor(model => model.Catergory, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Catergory", new SelectList(new[] {"Chef Specials","Deserts","Drinks","Main Courses","Sides",
                                                                "Starters" ,"Salads"}))
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Description, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Description, new { @cols = "80", @rows = "4" })
                @Html.ValidationMessageFor(model => model.Description)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Price, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Price)
                @Html.ValidationMessageFor(model => model.Price)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Add Item" class="btn btn-default" />
                <div class="btn btn-default">
                    @Html.ActionLink("View Menu", "Menu", "Details", new { Id = ID })
                </div>
            </div>
        </div>
    </div>
}

将数据从控制器传递到视图ASP.NET

因为您正在返回重定向操作。您应该使用tempdata或session变量将值保存在菜单中,当它是一个重定向动作时,它应该保存该值。

当你重定向时,你会丢失ViewData的内容。TempData是保留的,所以如果有可能重定向,可以使用它。我不知道ViewBag你可以测试一下

您已经通过视图模型传递了其他值,为什么不在视图模型中创建一个新属性并将其传递给视图呢?