c# - Display image dynamically with ViewBag -
i want display , change image dynamically in same view. have tried use code: use mvc 3 viewbag dynamically change image
and this: pass image controller , display in view using viewbag in asp.net mvc 3
but didn't work.
here index.cshtml
:
@using (html.beginform("showfile", "home", formmethod.post, new { enctype = "multipart/form-data" })) { @html.textbox("imageid") <input type="submit" value="ok" class="submit" /> } <img src="@viewbag.foto" alt="images" />
my homecontroller.cs
:
public actionresult index() { return view(); } public actionresult showfile(string imageid) { var dir = server.mappath("/images/profile"); var path = path.combine(dir, imageid + ".jpg"); if (system.io.file.exists(path)) { viewbag.foto = path.tostring(); } return redirecttoaction("index", "home"); }
i believe there 2 issues code sample have provided.
the first issue providing full path image tag. setting viewbag.foto property contents of server.mappath()
combined image resulting img
tag similar to:
<img src="c:\your-local-path-here\images\profiles\image.jpg" alt="images"/>
but want similar to:
<img src="/images/profile/image.jpg" alt="images"/>
the second issue setting viewbag
property image path , performing redirect. when return redirect browser content of viewbag
not maintained next request index()
action.
the controller code therefore changed to:
public viewresult index() { return view(); } [httppost] public viewresult showfile(string imageid) { var virtualpath = string.format("~/images/profile/{0}.jpg", imageid); if (system.io.file.exists(server.mappath(virtualpath))) { viewbag.foto = virtualpathutility.toabsolute(virtualpath); } return view("index"); }
additionally, not need specify new { enctype = "multipart/form-data" }
in form (see what enctype='multipart/form-data' mean?).
Comments
Post a Comment