【发布时间】:2014-02-21 11:18:49
【问题描述】:
我正在尝试使用 ASP .NET MVC 4 上传文件。我完全按照 these 的说明进行操作,但是当我提交文件时,我总是发现自己使用了错误的 Index 方法(尽管这会呈现表格)。我的代码:
控制器:
public class ActivationController : Controller
{
public ViewResult Index()
{
return View(new ActivationIndexViewModel());
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// NEVER GET HERE!
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
}
查看:
<form class="form-horizontal" role="form">
<div class="container-fluid">
<div class="row">
<div class="form-group">
<label class="col-sm-2 control-label" for="file">Serial number</label>
<div class="col-sm-10">
@using (Html.BeginForm("Index", "Activation", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="Load" class="btn btn-primary" />
<p class="help-block">Select a file</p>
}
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="col-sm-2 control-label">Продукт</label>
<div class="col-sm-10">
@Html.DropDownListFor(m => m.SelectedProductId,
@Model.ActivatableProductsAsSelectList, new { @class = "form-control" })
<p class="help-block">Select a product</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="col-sm-2 control-label">Options</label>
<div class="col-sm-10">
<div class="table-responsive">
<table class="table"/>
</div>
</div>
</div>
</div>
</div>
路由配置:
routes.MapRoute(
name: "Activation",
url: "{controller}/{action}",
defaults: new { controller = "Activation", action = "Index" }
);
我做错了什么?
【问题讨论】:
-
您的代码没有问题。我对其进行了测试,它按预期工作。请检查代码的其他部分。或者分享一下相关代码,这样我们就可以检查文件上传哪里出错了。
-
我认为您的视图可能有其他部分导致了问题。请发布完整视图。
-
@ramiramilu 我也用 Bootstrap,会不会有问题?
-
我认为引导程序不会产生任何问题。因为我在您附加的代码中没有看到任何特定的引导代码。但是尝试创建一个示例 MVC 项目并实现此代码,它将按预期工作。
-
@ramiramilu 添加了完整视图
标签: asp.net-mvc asp.net-mvc-4 routing