I can't figure out how to return a result from my controller to my view without completely overriding the content on the page.
Here is what I am doing:
View
@using (Html.BeginForm("FileUpload", "Test", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function () {
});
</script>
Controller:
[HttpPost]
public JsonResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
using (Image image = Image.FromStream(file.InputStream, true, true))
{
if (image.Width >= 100 && image.Width <= 160 && image.Height >= 100 && image.Height <= 160)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath(Url.Content("~/img/profile/")), fileName);
file.SaveAs(path);
ViewBag.Message = "success";
return Json("success");
}
}
}
ViewBag.Message = "failed";
return Json("failed");
}
http://www.domainname.com/Test/Index
It changes to: http://www.domainname.com/Test/FileUpload and I get this:
or this:
I know how to return Json to a View when called via jquery such as
$("#btn1").click(function () {
$.ajax({
url: '@Url.Action("IndexPost", "Test")',
type: "POST",
data: {
str1: $("#txt1").val(),
str2: $("#txt2").val(),
str3: $("#txt3").val()
},
success: function (data) {
$("#txt4").val(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
},
complete: function () { }
});
});
but I am lost when it comes to having to use @using (Html.BeginForm(...))
I can successfully upload an image, but the problem I need help with is how do I maintain the page as it is, but have it look like this instead?:
or
Edit:
View 2 (using same Controller action and switching JsonResult and ActionResult file is still always null regardless):
<form>
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" id="btnSubmit" class="submit" />
</form>
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var formData = new FormData($("form").get(0));
$.ajax({
url: '@Url.Action("FileUpload", "Test")',
type: "POST",
data: formData,
processData: false,
contentType: false
});
return false;
});
});
</script>
Answer from Stephan Muecke: I was missing tags.
His answer: how to append whole set of model to formdata and obtain it in MVC