- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个基本的 asp.net c# 应用程序,它有一个表单可以将一些数据提交到数据库,这个表单有一个上传按钮来上传文件。
最初,有一个问题:我无法在不上传文件的情况下提交表单,它给出了一个错误 [object reference not set to an instance of an object],这意味着上传文件是一个必须在提交表单之前,所以为了解决这个问题,我在我的 Controller 中做了一些更改。
现在即使我没有上传任何东西它也会提交表单,但新的问题是当我上传文件并提交时它仍然会成功提交表单但它不会上传实际文件。
这是模型:
public class Events
{
public int Id { get; set; }
public string title { get; set; }
public string amount { get; set; }
public string Finance_Approval { get; set; }
public DateTime date_time { get; set; }
public string file_one { get; set; }
[NotMapped]
public HttpPostedFileBase file1 { get; set; }
}
这是 Controller :
public ActionResult Index()
{
return View();
}
public ActionResult Request(Events e)
{
if (e.file_one==null)
{
_context.evt.Add(e);
_context.SaveChanges();
return Content("Added");
}
else
{
string filename = Path.GetFileNameWithoutExtension(e.file1.FileName);
string extension = Path.GetExtension(e.file1.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
e.file_one = "PM_Files/" + filename;
filename = Path.Combine(Server.MapPath("~/PM_Files/"), filename);
e.file1.SaveAs(filename);
_context.evt.Add(e);
_context.SaveChanges();
return Content("Added");
}
}
这是 Razor View :
@using (Html.BeginForm("Request", "Requester", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
@Html.LabelFor(a => a.title)
@Html.TextBoxFor(a => a.title, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(a => a.amount)
@Html.TextBoxFor(a => a.amount, new { @class = "form-control" })
</div>
<div class="form-group">
<label>Select the file word or pdf etc</label>
<input type="file" name="file1" />
</div>
<button class="btn btn-primary">Request</button>
}
最佳答案
确切的问题是您正在根据 file_one
字符串属性检查 null,该属性始终具有 null 值,因为在 View 页面内没有与其关联的表单控件。您应该检查 HttpPostedFileBase
而不是:
[HttpPost]
public ActionResult Request(Events e)
{
if (e.file1 != null && e.file1.ContentLength > 0)
{
// save the file
return Content("Added");
}
else
{
// do something else
return Content("Added");
}
}
如果上面的标准 HttpPostedFileBase
检查不起作用,您应该尝试 Request.Files
来获取文件信息:
[HttpPost]
public ActionResult Request(Events e)
{
if (Request.Files.Count > 0)
{
foreach (string files in Request.Files)
{
if (!string.IsNullOrEmpty(files))
{
// save the file
}
}
return Content("Added");
}
else
{
// do something else
return Content("Added");
}
}
注意事项:
1) 表单使用FormMethod.Post
,因此 Controller 操作应该使用[HttpPost]
属性。
2) [NotMapped]
attribute仅用于数据模型以排除实体映射到数据库中的列 - 它不用于 View 模型,只需将其删除。
关于c# - 如何在 asp.net c# 应用程序中放置一个可选的文件上传按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293357/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!