I have a method set up that uses jquery form for a file upload – after the upload I wanted to update a layer. Here is my code…
The problem is that the method is a JsonResult, and I can't figure out how to invoke the updating of another part of the page after it runs. Any suggestions?
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<script type="text/javascript">
$(function() {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function() {
$("#ajaxUploadForm").block({ message: '<img src="<%= ResolveUrl("~/content/images/busy.gif") %>" /> Uploading file...' });
},
success: function(result) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
//$.growlUI(null, result.message);
},
error: function(xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
</script>
<form id="ajaxUploadForm" action="<%= Url.Action("Upload", "Pictures")%>" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" />
</div>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</form>
public FileUploadJsonResult Upload(HttpPostedFileBase file)
{
var fileName = System.IO.Path.Combine(Request.MapPath("~/Uploads"),
System.IO.Path.GetFileName(file.FileName));
file.SaveAs(fileName);
Test();
// Return JSON
return new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}
Best Solution
JSON data is basically identical to a hash or dictionary in javascript.
You can simply take the json result in your
success(result)
function and dig into it, the way you normally would a dictionary in Javascript. For example:The snippet above would add 'value2' to a div with an
id="divToUpdate"
.You won't be able to use any server-side views or partial views to render the html. Instead you will have to use JQuery to generate any additional HTML since the JSON is being processed on the client. Its one or the other, basically.
One workaround is to return some javascript inside the partial view.