我如何在 MVC 中获取 Post 上的许多文本框的值

How can i take many textboxes' value on Post in MVC

我对 MVC 有疑问,但首先我对我的英语感到抱歉 :D 。 现在我正在尝试为用户制作一个表单,当我想连接到数据库的值时我遇到了一个严重的问题。

我的表格是这样的:https://i.hizliresim.com/vJ6r2p.png

型号:

[Table("Testers")]
    public class Testers
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }

        [StringLength(50),Required]
        public string testerName { get; set; }

        public ICollection<Scores> Scores { get; set; }
    }
    [Table("Technologies")]
        public class Technologies
        {
            [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int ID { get; set; }
            [StringLength(50)]
            public string technologyName { get; set; }
            [StringLength(50)]
            public string type { get; set; }
        }
    [Table("Scores")]
    public class Scores
    {
        [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        [DefaultValue(0)]
        public int score { get; set; }

        public virtual Testers tester { get; set; }
        public virtual Technologies technology { get; set; }
    }

视图模型:

  public class TechnologiesView
    {
        public List<Technologies> Technologies { get; set; }
        public Scores Scores { get; set; }
    }

控制器:

public ActionResult Page2()
        {
            TechnologiesView allTechs = new TechnologiesView();
            allTechs.Technologies = db.Technologies.ToList();
            return View(allTechs);
        }

查看:

@model TechnologiesView
@{
    ViewBag.Title = "Page2";
}
<style>
    #lang {
        font-size: 15px;
        color: gray;
    }

    #tech {
        font-size: 13px;
        color: gray;
    }
</style>

<div class="container">
    <div class="row col-xs-12 bilgi" style="color:black">
        @HelperMethods.Title("Kendini Skorla!")
        <br />
        <i>Bilgi Düzeyini 0 ile 5 puan arasında notlar mısın? (0=Hiç 5= İleri Seviye)</i>
    </div>
</div>

<hr />
@using (Html.BeginForm())
{
    <div class="container-fluid" style="padding-left:50px; margin:0px">
        <div class="row" id="lang">

            @foreach (Technologies techs in Model.Technologies)
            {
                if (techs.type == "lang")
                {
                    <div class="col-md-1 col-sm-2 col-xs-6">
                        @(techs.technologyName)
                    </div>
                    <div class="col-md-1 col-sm-2 col-xs-6">
                        (@(Html.TextBoxFor(x => x.Scores.score, new
                     {
                         id = techs.ID,
                         name = "techID",
                         style = "display:inline; width:20px; height:20px; font-size:smaller; padding:0px; text-align:center",
                         @class = "form-control"
                     })))
                    </div>
                }
            }
        </div>
        <hr style="color:black" />
        <div class="row" id="tech">
            @foreach (Technologies techs in Model.Technologies)
            {
                if (techs.type == "tech")
                {
                    <div class="col-md-1 col-sm-2 col-xs-6" id="tech">
                        @(techs.technologyName)
                    </div>
                    <div class="col-md-1 col-sm-2 col-xs-6">
                        @Html.HiddenFor(x=>techs.ID)
                        (@(Html.TextBoxFor(x => x.Scores.score, new
                     {
                         id = techs.ID,
                         name = "techID",
                         style = "display:inline; width:20px; height:20px; font-size:smaller; padding:0px; text-align:center",
                         @class = "form-control"
                     })))
                    </div>
                }
            }
        </div>
        <hr />
        <div class="row col-xs-12" id="lang">
            <span>Kullandığınız IDE’ler (yazınız)</span>
            <br />
            <div style="margin-bottom:10px; text-align:center">
                @HelperMethods.TextArea("Ide", 3)
            </div>
        </div>
        <div style="text-align:right; margin-bottom:10px">
            @HelperMethods.Button("btnPage2")
        </div>
    </div>
}

现在用户必须为每种技术或语言给 him/herself 打分,此后我想当用户点击按钮 "Follow the next page(it's turkish)" 我将 select 最后保存的用户来自测试人员的 maxID 值,我必须将分数与技术和测试人员联系起来,但我不知道如何获取文本框的值以及哪个技术的值是 post 上的此值:D

您生成的表单控件与您的模型完全没有关系(无论如何这也是错误的)。使用 HtmlHelper 方法时切勿尝试更改 name 属性(也没有理由更改 id 属性)

接下来,您不能使用 foreach 循环为集合生成表单控件。您需要一个 for 循环或 EditorTemplate 来使用索引器生成正确的 name 属性。详细解释请参考

那么你不能在循环中使用 if 块(除非你为集合索引器包含一个隐藏的输入),因为默认情况下 DefaultModelBinder 要求集合索引器从零开始并且是连续。

首先创建视图模型来表示您想要在视图中display/edit的内容。

public class ScoreVM
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Score { get; set; }
}
public class TechnologiesVM
{
    public List<ScoreVM> Languages { get; set; }
    public List<ScoreVM> Technologies { get; set; }
    public string Notes { get; set; } // for your textarea control
}

请注意,您可能想要添加验证属性,例如 Score 属性

[Range] 属性

在 GET 方法中,初始化并填充您的视图模型并将其传递给视图

public ActionResult Page2()
{
    IEnumerable<Technologies> technologies = db.Technologies;
    TechnologiesVM model = new TechnologiesVM
    {
        Languages = technologies.Where(x => x.type == "lang")
            .Select(x => new ScoreVM{ ID = x.ID, Name = x.technologyName }).ToList(),
        Technologies = technologies.Where(x => x.type == "tech")
            .Select(x => new ScoreVM{ ID = x.ID, Name = x.technologyName }).ToList(),
    };
    return View(model);
}

并在视图中

@model TechnologiesVM
....
@using (Html.BeginForm())
{
    ....
    @for (int i = 0; i < Model.Languages.Count; i++)
    {
        @Html.HiddenFor(m => m.Languages[i].ID)
        @Html.HiddenFor(m => m.Languages[i].Name)
        @Html.LabelFor(m => m.Languages[i].Score, Model.Languages[i].Name)
        @Html.TextBoxFor(m => m.Languages[i].Score)
        @Html.ValidationMessageFor(m => m.Languages[i].Score)
    }
    @for (int i = 0; i < Model.Languages.Count; i++)
    {
        .... // repeat above
    }
    @Html.LabelFor(m => m.Notes)
    @Html.TextAreaFor(m => m.Notes)
    @Html.ValidationMessageFor(m => m.Notes)

    <input type="submit" />
}

并且 POST 方法将是

public ActionResult Page2(TechnologiesVM model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    ... // save the data and redirect
}