c# - 从 URL 到数据库的传递 ID 为空
问题描述
我的视图看起来像这样 我的 url 链接http://localhost:63897/UploadImages?id=1361。1361是我的pr_id
。我需要将 1361 的 id 从 url 传递到数据库,但它会为空。
这是我的控制器代码:
public ActionResult UploadImages(int id) {
ViewBag.prid = id;
return View();
}
[HttpPost]
public ActionResult UploadImages([Bind(Include = "id,photo_url,photo_caption,photo_credit,pr_id")] Photo photos, HttpPostedFileBase photo_file)
{
if (ModelState.IsValid)
{
if (photo_file != null && photo_file.FileName != null && photo_file.FileName != "")
{
try
{
string path = Path.Combine(Server.MapPath("~/Images/Releases"), Path.GetFileName(photo_file.FileName));
photo_file.SaveAs(path);
string f1 = path.Substring(path.LastIndexOf("\\"));
string[] split = f1.Split('\\');
string newpath = split[1];
string imagepath = "~/Images/Releases/" + newpath;
photos.photo_url = imagepath;
_db.Photos.Add(photos);
_db.SaveChanges();
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
return RedirectToAction("List");
}
}
return View();
}
看法 :
@Html.HiddenFor(model => model.pr_id, new { @Value = ViewBag.id })
解决方案
您的视图包字典项的键是prid
. 但是在您的视图代码中,您使用的是不同的键。
使用ViewBag.prid
. 也可以使用Hidden
辅助方法。
@Html.Hidden("pr_id", new { @value = ViewBag.prid })
或者只是编写纯 HTML 并设置value
属性值。
<input type="hidden" name="pr_id" value="@ViewBag.prid" />
检查页面的视图源以确认正确的value
属性设置为带有名称的隐藏输入元素pr_id
假设您修复了错误的 ViewBag 键名,您现有的方法基本上会生成以下标记
<input Value="23" name="pr_id" type="hidden" value="0" />
记住, Value != value
这是我不使用像 ViewBag 这样的动态东西的主要原因之一。您犯了这样的愚蠢错误,并且 IDE/编译器没有警告/错误。它只是默默地失败:(如果您使用强类型视图模型,编译器会在您打错字时抱怨。
也不要使用该*For
方法并尝试手动覆盖 value/id/name 等。帮助程序旨在正确设置 value/name/id 属性值。考虑使用视图模型并将这些For
方法与它们一起使用。那将是更少的代码。
如果您的视图模型有一个名为 的pr_id
属性,请在您的 GET 操作中设置该属性值,将该视图模型发送到视图和视图中(该视图模型是强类型的),只需调用HiddenFor
该属性的方法
@Html.HiddenFor(a=>a.pr_id);
推荐阅读
- java - 出现五个随机数后如何让我的屏幕变黑?
- haskell - 通过匹配获取数据元素
- android - AWS 证书 - 无法识别的密钥库格式:null
- r - 如何将多个变量放在列内作为r中的一个因素
- terraform - Terraform 遍历列表
- android - OmdB API 未在我的 TextViews 中显示结果
- python - 读取、编辑,然后将文本 (.txt) 文件保存为列表
- sql-server - 使用表变量而不是临时表时存储过程中的性能问题
- c# - 选择具有最大值的实体
- python - 如何在安装 Scipy for Scikit learn 时修复“E: Package 'libatlas-dev' has no installation Candidate”?