注意事项:
1.提交form,必须引用jquery.form.min.js
2.不要使用mvc自带的Ajax.Form()
1.页面cshtml
<form name="frmInput" id="frmInput" method="post" action="@Url.Action(ViewContext.RouteData.Values["Action"].ToString())" enctype="multipart/form-data" >
<input id="f1" name="f1" type="file">
<input type="button" value="保存" onclick="Input.Save(this)" class="btn-8" />
</from> Input.Save = function (e) {
$('#frmInput').ajaxSubmit({
url: Url,
error: function (request) {
alert('保存出错,请重试!');
},
success: function (data) {
var dataObj = eval("(" + data + ")");//转换为json对象
//方法二
//var dataObj=jQuery.parseJSON(data);
if (dataObj.IsOK) {
//刷新列表
alert("保存成功!");
}
else {
alert('保存失败!');
}
}
});
}
2.后台
示例1,忘记什么时候写的,以后看到再修改补充
[HttpPost]
public JsonResult Create(MerchantsModel model, FormCollection form)
{
return new JsonResult() { ContentType = "text/html", Data = object };// return Json(result, "text/html", Encoding.UTF8);
}
示例2
[HttpPost]
public ActionResult void Create(Model modelName, FormCollection form)
{
var requestFiles = Request.Files;//HttpFileCollectionBase
if (requestFiles.Count > )
{
for (int i = ; i < requestFiles.Count; i++)
{
//此块代码仅作示例
//文件名称 requestFiles[i].FileName
var postedfile = requestFiles[i];//HttpPostedFileBase
var savePath="d://d.jpg";
postedfile.SaveAs(savePath);
}
}
return Json(result, "text/html", Encoding.UTF8);
}
3. 解决问题
返回<pre style="word-wrap: break-word; white-space: pre-wrap;">....</pre> 的问题
4. HttpPostedFile 转为HttpPostedFileBase
它们之间是两个独立的东西,需要通过HttpPostedFileWrapper转换,犹如 HttpContext和HttpContextBase要通过HttpContextWrapper 包装,是.NET3.5时才有的,使用.NET2.0类库可能会遇到,这里记录下。
public bool Upload(HttpPostedFile file)
{
HttpPostedFileBase hpfb = new HttpPostedFileWrapper(file);
return false;
}
来自:http://www.cnblogs.com/Kummy/archive/2013/02/27/2934608.html
推荐写法:Application_Start中统一检测
private void CheckUploadDirectory()
{
string assemblyDirectory = AppDomain.CurrentDomain.BaseDirectory;
assemblyDirectory = Path.Combine(assemblyDirectory, "Upload");
if (!Directory.Exists(Path.Combine(assemblyDirectory, "Logo")))
{
Directory.CreateDirectory(Path.Combine(assemblyDirectory, "Logo"));
}
if (!Directory.Exists(Path.Combine(assemblyDirectory, "Problems")))
{
Directory.CreateDirectory(Path.Combine(assemblyDirectory, "Problems"));
}
}