MikeW
MikeW

Reputation: 4809

How can I pass data from a PartialView back to the Page in MVC

I have this setup on my page roughly - a file upload control, and a div (#changingBit) that swaps in different partial views with "List" being the default.

            <td><input type="file" name="Image" /></td>
            <td><input type="submit" value="Save" /></td>

                <div id="changingBit">
                    @Html.Partial("List", Model.Things)    
                </div>

These partial views basically list folders and files. I need to be able to pass a param ( like current Folder path ) which is available inside the actions for the partial views, to the upload controller action.

I tried adding this in the List / Edit Partial views

ViewData["id"] = some value...

But this is always null inside the main page. How do I grab that value inside the upload controller action?

Thanks!

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Upload(HttpPostedFileBase image)
    {

       //some magic to access a partial views variable
       // .............
       //

        if (image != null)
        {
            var fileName = Path.GetFileName(image.FileName);
            var path = Path.Combine(Server.MapPath("~/Directories/YourDirectory"), fileName);
            image.SaveAs(path);
        }
        return RedirectToAction("Index");
    }
    [HttpGet]
    public ActionResult Edit(int id)
    {
         ViewData["id"] = id;                 <--- how to get this file inside Upload action?
         ...

    }

Edit:

Ended up doing this on the main page

<input type="hidden" name="currentIdSelection" value="@Model.CurrentIdSelection" />

which works for now, I changed the model I passed into the "Edit" partial view to store another value. There's probably a more MVC way to do this tho...

Upvotes: 1

Views: 554

Answers (1)

Pieter Germishuys
Pieter Germishuys

Reputation: 4886

As a note, ViewData only lives in a single request. If you want to pass information around like what you are doing right now you can use TempData.

Upvotes: 1

Related Questions