0

I am having a issue passing a variable from a controller to a view. I have created an actionresult that allows users to add meals to a restaurant menu. I need the menuID in a html action link to access the menu details page. But when I run the page ViewData["MenuID"] returns as null even though menuID has a value in the controller action result. Is there another way to send data from a controller to a view?

Create action result

[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();

        }

Create CSHTML Page

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

3 Answers 3

1

because you are returning a redirecttoaction. you should use tempdata or session variable to save the value in the menuid and that should hold the value when it's a redirecttoaction.

Sign up to request clarification or add additional context in comments.

Comments

1

When you do a redirect you lose the contents of ViewData. TempData is preserved though, so you can use that if a redirect is a possibility. I don't know about ViewBag so you might test that.

1 Comment

FWIW, ViewData and ViewBag are the same thing, just accessed differently. You can put a value into ViewBag (e.g. ViewBag.SomeValue = 1) and pull it out using ViewData (e.g. ViewData["SomeValue"]) and vice versa.
0

You already are passing other values through a view model, why not make a new property in that viewmodel and pass it along to the view?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.