我遇到了將控制器變量傳遞給視圖的問題。我創建了一個動作結果,允許用戶在飯店菜單中添加餐點。我需要html操作鏈接中的menuID來訪問菜單詳細信息頁面。但是當我運行頁面ViewData["MenuID"]
返回爲null,即使menuID在控制器操作結果中有一個值。是否有另一種方式將數據從控制器發送到視圖?從控制器傳遞數據以查看ASP.NET
創建行動結果
[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>
}
FWIW,ViewData和ViewBag是相同的東西,只是訪問方式不同而已。您可以將值放入ViewBag(例如,ViewBag.SomeValue = 1)中,並使用ViewData(例如ViewData [「SomeValue」])將其拉出,反之亦然。 –