ASP.NET MVC,3 个静态下拉列表。它应该一次解析所有值,但它没有。



大家好,对不起,短帖子; 0)

i具有带有TRE下拉列表的视图,然后我将其应立即解析到数据库的表单,但事实并非如此。

这是我的代码:

视图....

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>SaveRatings</title>
</head>
<body>
    <div> 
        @using (Html.BeginForm("SaveRatings", "Scout"))
        {
            int id = 3;
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)
            for (int i = 0; i < id; i++)
            {
                @Html.DropDownList("Value", (IEnumerable<SelectListItem>)ViewBag.Value, "Vælg en værdi fra 1 - 20", new { @class = "form-control" })<br/>
            }



            <input type="submit" value="Save" />
        }

    </div>
</body>
</html>

控制器和VitureDropDownList方法

   public ActionResult SaveRatings()
        {
            ValueDropDownList();
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SaveRatings(string Value)
        {
            using (Connection db = new Connection())
            {
                List<Rating> rt = new List<Rating>();
                rt.Add(new Rating
                {
                    Value = Value
                });
                //For every obejct in the list, it should add the items....
                foreach (var item in rt)
                {
                    db.Ratings.Add(item);
                }

                db.SaveChanges();

            }
            return View("GetProperties");
        }

VitureDropDownList方法

 public void ValueDropDownList()
    {
        List<SelectListItem> valueitems = new List<SelectListItem>();
        valueitems.Add(new SelectListItem { Text = "1", Value = "1" });
        valueitems.Add(new SelectListItem { Text = "2", Value = "2" });
        valueitems.Add(new SelectListItem { Text = "3", Value = "3" });
        ViewBag.Value = valueitems.ToList();
    }

您的当前视图代码将渲染3个选择元素,名称为" Value"。提交表单时,表单数据将具有3个键,其中名称为" value",每个值是您选择的选项值。

现在,由于它正在发送一个数组(因为所有三个下拉名称均相同),因此您需要将操作方法参数删除到数组。然后,您可以循环浏览此数组并保存它。

public ActionResult SaveRatings(string[] Value)
{
    using (var db = new Connection())
    {
        foreach (var item in Value)
        {
            var t=new Rating
            {
                Value = item
            };
            db.Ratings.Add(t);                    
        }
        db.SaveChanges();
    }
    return RedirectToAction("Index");
}

最新更新