【问题标题】:passing data from controller to view ASP.NET从控制器传递数据以查看 ASP.NET
【发布时间】:2014-03-19 02:35:54
【问题描述】:

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

创建操作结果

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

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-controller


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • FWIW、ViewData 和 ViewBag 是同一个东西,只是访问方式不同。您可以将一个值放入 ViewBag(例如 ViewBag.SomeValue = 1)并使用 ViewData 将其拉出(例如 ViewData["SomeValue"]),反之亦然。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-27
        • 2021-04-19
        • 2012-12-22
        • 1970-01-01
        • 2019-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多