2011-02-04 79 views
2

我有一個上傳文件的控制器。我想返回一個帶有bool成功的json結果(如果成功上傳,否則爲false)和消息(這可能是發生的錯誤消息,或者鏈接到文件或鏈接到圖像,取決於上傳的內容)。MVC返回Json結果

解決這個問題的最好方法是什麼?

我有這個

public class UploadedFile 
{ 
    public bool Success { get; set; } 

    public string Message { get; set; } 
} 

然後在我的控制器中我會成功設置爲true /或/和虛假信息,以<a href OR <img

我在正確的軌道上?

我如何解析這個視圖,以便當圖像顯示圖像時,如果鏈接顯示鏈接,如果錯誤只是提醒錯誤。 謝謝

回答

4

你爲什麼要解析它?你不能提供你在Json中返回的更多信息嗎?

也許這樣的事情:

public class UploadedFile 
{ 
    public bool Success { get; set; } 
    public string Message { get; set; } 
    public Kind MessageKind { get; set; } 
} 

public enum Kind 
{ 
    Error, 
    File, 
    Image 
} 

根據MessageKind,你只需要使用適當的HTML顯示結果。

4

你在正確的軌道上。我會建議你使用jquery form plugin這將允許你AJAXify的<form>和處理成功案例。

實施例:

型號:

public class UploadedFile 
{ 
    public bool Success { get; set; } 
    public string Url { get; set; } 
    public string Message { get; set; } 
} 

控制器:

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" 
     }); 
    } 
} 

檢視:

<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> 

和UploadedFile的部分:

@model AppName.Models.UploadedFile 
@{ 
    Layout = null; 
} 

@if (Model.Success) 
{ 
    <img src="@Model.Url" alt="" /> 
} else { 
    @Model.Message 
}