值'1'无效(asp.net)

问题描述 投票:0回答:1

我正在尝试填充表格,但是当我从下拉列表中选择一个值并在下拉列表下方发布错误消息时,将显示一条错误消息,并显示消息“值'1'无效”。我搜索了解决方案,也许这是重复的帖子,但是没有其他帖子对我有用。

问题在商店属性中。

模型

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Image { get; set; }

    [ForeignKey("Shop")]
    public int ShopId{ get; set; }
    public virtual Shops Shop { get; set; }

Controller

    [Authorize(Roles = "Registered,Admin")]
    public ActionResult Create()
    {
        ViewBag.ShopTable= new SelectList(db.Shops, "Id", "ShopName");
        return View();
    }

Post Controller

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Shop,Name,Image")] ShopType shopType)
    {
        if (ModelState.IsValid)
        {
            db.ShopType.Add(shopType);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.ShopTable= new SelectList(db.Shops, "Id", "Shopname");

        return View(shopType);
    }

查看

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Shop, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Shop, new SelectList(ViewBag.ShopTable, "Value", "Text"), new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Shop, "", new { @class = "text-danger" })
        </div>
    </div>
asp.net-mvc
1个回答
0
投票

商店是一个对象,因此您无法使其下拉。因此,您需要将shop更改为shopId。

示例:

   [Authorize(Roles = "Registered,Admin")]
    public ActionResult Create()
    {
        ViewBag.ShopTable= db.Shops.Select(s=>new SelectListItem {Value=s.Id.ToString(), Text =s.ShopName}).ToList();
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,ShopId,Name,Image")] ShopType shopType)
    {
        if (ModelState.IsValid)
        {
            db.ShopType.Add(shopType);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        VViewBag.ShopTable= db.Shops.Select(s=>new SelectListItem {Value=s.Id.ToString(), Text =s.ShopName}).ToList();

        return View(shopType);
    }
© www.soinside.com 2019 - 2024. All rights reserved.