如何通过MVC4上传文件并获取json响应

时间:2014-04-11 08:26:16

标签: html ajax asp.net-mvc asp.net-mvc-4

我尝试使用MVC4语法上传文件

@using (Html.BeginForm("ImportCsv","ASPolicy", FormMethod.Post, new {enctype = "multipart/form-data"}))
            {
                <input type="file" name="file" style="display: none"/>
                <input type="text" name="cid" value="'@ViewData["cid"]'" style="display: none"/>
                <input type="submit" value="upload" style="display: none"/>
            }

我的控制器看起来像

public JsonResult ImportCsv(HttpPostedFileBase file, String cid)
    {

        IPRestriction ipRestriction = new IPRestriction();
        List<string> ipList = new List<string>();

        using (BinaryReader b = new BinaryReader(file.InputStream))
        {
            byte[] binData = b.ReadBytes(Convert.ToInt32(file.InputStream.Length));
            string result = System.Text.Encoding.Unicode.GetString(binData);

            TextReader textReader = new StringReader(result);
            CsvReader csv = new CsvReader(textReader, new CsvConfiguration() {Delimiter = "\t"} );

            while (csv.Read())
            {
                string accountNumber = csv.GetField(0);
                string ip = csv.GetField(1);
                ipRestriction.accountNumber = accountNumber;
                ipList.Add(ip);
            }

            ipRestriction.ipAllowList = ipList.ToArray();
        }

        String jsonStr = JsonConvert.SerializeObject(ipRestriction);
        return Json(jsonStr, JsonRequestBehavior.AllowGet);
    }

这个看起来不起作用因为点击了所有时间提交按钮,它将落到这个控制器并尝试用json重定向页面我已经返回。

所以,无论如何都要上传文件并获取json响应,我需要使用这个json响应来呈现此页面中的内容

1 个答案:

答案 0 :(得分:0)

你需要ajax post而不是Html.BeginForm()。 因此,使用jquery forms pluginAjax.BeginForm()可以轻松完成任务。 以下是步骤。

包括图书馆

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

查看

//Returned Json value will be here.
<div id="result"></div>

@using (Ajax.BeginForm("ImportCsv", "ASPolicy", new AjaxOptions() { HttpMethod = "POST" , UpdateTargetId = "result" }, new { enctype = "multipart/form-data"}))
{
    @Html.AntiForgeryToken()
    <input type="file" name="files"><br>
    <input type="submit" value="Upload File to Server">
}

<强>控制器

public JsonResult ImportCsv(IEnumerable<HttpPostedFileBase> files, String cid)
{
    if (files != null)
    {
        foreach (var file in files)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // TODO: need to define destination
                var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                file.SaveAs(path); //upload for example
            }
        }
    }

    //String jsonStr = JsonConvert.SerializeObject(ipRestriction);
    return Json(jsonStr, JsonRequestBehavior.AllowGet); //Now return Json as you need.
}