So I have ajax file upload partial (using Jquery Form plugin), it’s working perfectly, but I don’t know to update model value after file uploading
<div>
@Html.Partial("PhotoUpload", Model.Place)
</div>
Here I’m calling partial and giving to it part of a model.
@model PlaceMap.DAL.Entities.Place
@using (Html.BeginForm("PhotoUpload", "Place", FormMethod.Post, new { @id = "photoUpload", enctype = "multipart/form-data" }))
{
{
@Html.ValidationSummary(true, "Image upload was unsuccessful")
@Html.HiddenFor(m => m.Photo)
<input type="file" id="file" name="file"/>
<input type="submit" id="sbm" />
}
}
This is view code of partial, accepting model and form for uploading
var options = {
url: "/Place/PhotoUpload",
dataType: "json",
clearForm: true,
resetForm: true,
success: showResponse
};
function showResponse(responseText, statusText, xhr, $form)
{
$('#photo').append('<img src="/Images/Places/' + responseText.Photo + '" />');
}
$('#photoUpload').submit(function ()
{
$('#photoUpload').ajaxSubmit(options);
return false;
});
Javascript code for plugin
[Authorize]
[HttpPost]
public ActionResult PhotoUpload(string Photo, HttpPostedFileBase file)
{
try
{
using (var ms = new MemoryStream())
{
//some logic here
return Json(new { Photo = filename });
}
}
catch (ArgumentException)
{
}
return PartialView();
}
Controller action code. It’s returning file name, it’s going to js function “showResponse” and appending image to div. It’s all work perfectly, but I have to write file name to @Model.Photo of this partial and I don’t know how to do it. Any suggestions?
One possibility is to use
text/plainfrom the server:and on the client manually parse:
Obviously you lust remove the
dataType: 'json'option for this to work.Another possibility is to follow what’s explained in the documentation and write a custom action result which will wrap your JSON response with the
<textarea>tags: