当我选择一个文件,并提交文件进行上传,我不能让我的模型文件路径的值。在控制它显示为空
。我究竟做错了什么?
<形式方法=邮报行动=/帐号/个人资料ENCTYPE =的multipart / form-data的>
<标签>将照片:LT; /标签>
<输入类型=文件名称=文件路径ID =文件/>
<输入类型=提交值=提交/>
< /形式GT;
公众的ActionResult资料(ProfileModel模型的FormCollection形式)
{
字符串路径= Convert.ToString(model.FilePath);
返回查看();
}
公共HttpPostedFileBase文件路径
{
得到
{
返回_filePath;
}
组
{
_filePath =价值;
}
}
公共BOOL UploadFile()
{
如果(文件路径!= NULL)
{
VAR文件名= Path.GetFileName(FilePath.FileName);
FilePath.SaveAs(@C:\+文件名);
返回true;
}
返回false;
}
解决方案
我不认为模型绑定与 HttpPostedFileBase
...
这应该工作,如果你把它从你的视图模型,做这样的:
公众的ActionResult资料(HttpPostedFileBase文件路径)
{
字符串路径= Convert.ToString(文件路径);
返回查看();
}
HTHS, 查尔斯
诗。这篇文章可能有助于解释的事情:ASP.NET MVC发布文件模型绑定时参数型号
When I select a file and submit the file for upload, I can't get the value of the File path in my Model. In the Controller it shows as null
. What am I doing wrong?
<form method="post" action="/Account/Profile" enctype="multipart/form-data">
<label>Load photo: </label>
<input type="file" name="filePath" id="file" />
<input type="submit" value="submit" />
</form>
public ActionResult Profile(ProfileModel model, FormCollection form)
{
string path = Convert.ToString(model.FilePath);
return View();
}
public HttpPostedFileBase FilePath
{
get
{
return _filePath;
}
set
{
_filePath = value;
}
}
public bool UploadFile()
{
if (FilePath != null)
{
var filename = Path.GetFileName(FilePath.FileName);
FilePath.SaveAs(@"C:\" + filename);
return true;
}
return false;
}
解决方案
I don't think model binding works with HttpPostedFileBase
...
It should work if you take it out of your ViewModel and do it like this:
public ActionResult Profile(HttpPostedFileBase filePath)
{
string path = Convert.ToString(filePath);
return View();
}
HTHs, Charles
Ps. This post could help explain things: ASP.NET MVC posted file model binding when parameter is Model