我有一个表单上传,但我想传递我的数据库的模型信息,以保存具有不同名称的文件.
这是我的剃刀观点:
@model CertispecWeb.Models.Container
@{
ViewBag.Title = "AddDocuments";
}
<h2>AddDocuments</h2>
@Model.ContainerNo
@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<input type='file' name='file' id='file' />
<input type="submit" value="submit" />
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器:
[HttpPost]
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"),
containers.ContainerNo);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
模型信息不会传递给控制器.我已经读过我可能需要更新模型,我该怎么做?
我认为这个表格有:
<!-- Bug (extra 'i') right here-----------v -->
<!-- was: <form method="post" enctype="mulitipart/form-data" action="/Task/SaveFile"> -->
<form method="post" enctype="multipart/form-data" action="/Task/SaveFile">
<input type="file" id="FileBlob" name="FileBlob"/>
<input type="submit" value="Save"/>
<input type="button" value="Cancel" onclick="window.location.href='/'" />
</form>
Run Code Online (Sandbox Code Playgroud)
这个代码在我的控制器中:
public ActionResult SaveFile( FormCollection forms )
{
bool errors = false;
//this field is never empty, it contains the selected filename
if ( string.IsNullOrEmpty( forms["FileBlob"] ) )
{
errors = true;
ModelState.AddModelError( "FileBlob", "Please upload a file" );
}
else
{
string sFileName = forms["FileBlob"];
var file …Run Code Online (Sandbox Code Playgroud) 我<input type="file" id="fileUpload" runat="server">用来在ASP.NET应用程序中上传文件.我想限制上传的文件类型(例如:限制为.xls或.xlsx文件扩展名).
JavaScript或服务器端验证都可以(只要服务器端验证将在文件上传之前进行 - 可能会上传一些非常大的文件,因此需要在上载实际文件之前进行任何验证) .
我有一个表单,它使用HttpPostedFileBase的默认绑定器绑定模型和文件上载.
这在使用Html.BeginForm()时工作正常.但是,我想使用AJAX执行相同的操作,因此我将其替换为Ajax.BeginForm(),相应地更改参数.
该模型仍然正确绑定,但我无法将文件上传绑定到HttpPostedFileBase.
这会绑定模型和文件上传:
<% using (Html.BeginForm("MapUpdateColumns", "RepositoryAdmin", FormMethod.Post, new { id = "UpdateDataset", enctype = "multipart/form-data" })) {%>
Run Code Online (Sandbox Code Playgroud)
这只会绑定模型:
<% using (Ajax.BeginForm("MapUpdateColumns", "RepositoryAdmin", new AjaxOptions { UpdateTargetId = "columnMappings" }, new { id = "UpdateDataset", enctype = "multipart/form-data" })) {%>
Run Code Online (Sandbox Code Playgroud)
控制器动作:
public ActionResult MapUpdateColumns(DatasetViewModel model, HttpPostedFileBase sourceFile)
Run Code Online (Sandbox Code Playgroud)
这应该是可能的,如果是的话,我做错了什么?谢谢.