首页 > 解决方案 > 从 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 })

标签: c#asp.netasp.net-mvcasp.net-mvc-5

解决方案


您的视图包字典项的键是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);

推荐阅读