【发布时间】:2014-04-11 17:12:22
【问题描述】:
我尝试使用 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响应来渲染这个页面中的内容
【问题讨论】:
-
你需要做的是异步提交表单。也许使用
jQuery.Post。如果您按照现在的方式提交表单,您将被重定向到 JSON 字符串页面。参考这篇博客:portfolio.planetjon.ca/2014/01/26/…
标签: html ajax asp.net-mvc asp.net-mvc-4