MVC Return Json result
I have a controller that uploads a file. I would like to return a json result with bool success (if successfully uploaded otherwise false) and message (this could be error message that occured OR link to a file OR link to an image, depending on what was uploaded).
What's the best way to approach this?
I have this
public class UploadedFile
{
public bool Success { get; set; }
public string Message { get; set; }
}
then In my controller I would set Success to true/or/false and Message to <a href
OR <img
am i on the right track?
How would i then parse this in the view so that when image it will show an image, if link show a link, if开发者_运维问答 error simply alert error. thanks
Why do you want to parse it ? Can't you provide more information in what you return in Json ?
Maybe something like that :
public class UploadedFile
{
public bool Success { get; set; }
public string Message { get; set; }
public Kind MessageKind { get; set; }
}
public enum Kind
{
Error,
File,
Image
}
Depending on the MessageKind
, you'll just have to use proper html to display the result.
You are on the right track. I would recommend you using the jquery form plugin which would allow you to AJAXify the <form>
and handle the success case.
Example:
Model:
public class UploadedFile
{
public bool Success { get; set; }
public string Url { get; set; }
public string Message { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var images = Server.MapPath("~/images");
var filename = Path.Combine(images, Path.GetFileName(file.FileName));
file.SaveAs(filename);
return View("UploadedFile", new UploadedFile
{
Success = true,
Url = Url.Content("~/images/" + Path.GetFileName(file.FileName))
});
}
return View("UploadedFile", new UploadedFile
{
Success = false,
Message = "Please upload a file"
});
}
}
View:
<script src="@Url.Content("~/scripts/jquery.form.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('form').ajaxForm(function (result) {
$('#result').html(result);
});
});
</script>
@using (Html.BeginForm("index", "home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="Save" />
}
<div id="result"></div>
and the UploadedFile partial:
@model AppName.Models.UploadedFile
@{
Layout = null;
}
@if (Model.Success)
{
<img src="@Model.Url" alt="" />
} else {
@Model.Message
}
精彩评论