Reputation: 11793
All , Say you have a code in a View
like this.
<img src='@Url.Action("GetCaptchaImg")' alt='' />
and of course there is an Action
named GetCaptchaImg
in the controller which return a FileContentResult
to View.
After open this view in FireFox. I found the Html code is
<img alt="" src="/Controllername/GetCaptchaImg" />
the src
is not the real physical path . So My question is what is the real physical path of this img
, How can I change the image by Ajax call to an Action
? Hope you can help me . thanks.
Upvotes: 0
Views: 186
Reputation: 2192
You can make an ajax call to the actionresult and from that return the name of the image and onsuccess of your ajax call change the image Alternatively you can do this thing, which i've implemented in my project Make your HTML form like this
@using (Html.BeginForm("ActionResult", "Controller", FormMethod.Post, new { @id = "ImgForm", @enctype = "multipart/form-data", name = "ImgForm", target = "UploadTarget" }))
{
}
Make an iframe as target of your form
<iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute;
left: -999em; top: -999em;"></iframe>
Your upload control
Then upload the Image and Show it on your form
function UploadImage() {
$("#ImgForm").submit(); //form id
}
function UploadImage_Complete() {
try {
//Check to see if this is the first load of the iFrame
if (isFirstLoad == true) {
isFirstLoad = false;
return;
}
//Reset the image form so the file won't get uploaded again
document.getElementById("ImgForm").reset();
//Grab the content of the textarea we named jsonResult . This shold be loaded into
//the hidden iFrame.
var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML);
if (newImg.IsValid) {
document.getElementById("dp").src = newImg.ImagePath;
document.getElementById('profile-pic').src = newImg.ThumbnailPath;
document.getElementById("change").style.display = "block";
}
// If there was an error, display it to the user
if (newImg.IsValid == false) {
alert(newImg.Message);
return;
}
}
catch (e) {
}
}
Your Action will look like this
public WrappedJsonResult ChangeImage(HttpPostedFileBase file)
{
}
and your WrappedJsonResult class will look likes
public class WrappedJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("<html><body><textarea id=\"jsonResult\" name=\"jsonResult\">");
base.ExecuteResult(context);
context.HttpContext.Response.Write("</textarea></body></html>");
context.HttpContext.Response.ContentType = "text/html";
}
}
Upvotes: 1