我如何在MVC中的Post上获取许多文本框的值 [英] How can i take many textboxes' value on Post in MVC

查看:81
本文介绍了我如何在MVC中的Post上获取许多文本框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对MVC有疑问,但首先,我对我的英语:D感到抱歉. 现在,我正在尝试为用户创建表单,当我想使用数据库连接值时遇到一个关键问题.

i have a problem about MVC, but first I am sorry for my english :D . Now i am trying to make a form for users and i have a critical issue when i want connect to values with database.

我的表单是这样的: 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; }
    }

ViewModels:

ViewModels:

  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>
}

现在,用户必须为每种技术或语言给自己打分,之后,我想在用户单击关注下一页(土耳其语)"按钮时从maxID值中选择最后保存的用户在Testers中,我必须将分数与技术和测试人员联系起来,但是我不知道如何获取文本框的值以及在发布后该值是哪个技术的值:D

Now user has to give a score to him/herself for every technologies or languages and after this i want to when user click to button "Follow the next page(it's turkish)" i will select the last saved user from maxID value in Testers and i have to connect scores with technologies and testers but i don't know how can i get textboxes' values and which technology's value is this value on post :D

推荐答案

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

You generating form controls which have no relationship at all to your model (which is also wrong anyway). Never attempt to change the name attribute when using the HtmlHelper methods (and there is no reason to change the id attribute either)

接下来,您不能使用foreach循环为集合生成表单控件.您需要一个for循环或EditorTemplate才能使用索引器生成正确的name属性.请参阅此答案以获取详细说明.

Next, you cannot use a foreach loop to generate form controls for a collection. You need a for loop or EditorTemplate to generate the correct name attributes with indexers. Refer this answer for a detailed explanation.

然后,您不能在循环内使用if块(除非您为集合索引器包括隐藏的输入),因为默认情况下,DefaultModelBinder要求集合索引器从零开始并且是连续的.

Then you cannot use a if block inside the loop (unless you include a hidden input for the collection indexer), because by default the DefaultModelBinder required collection indexers to start at zero and be consecutive.

首先从创建视图模型开始,以表示您想要在视图中显示/编辑的内容.

First start by creating view models to represent what your want to display/edit in the view.

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]属性

Note you will probably want to add validation attributes such as a [Range] attribute for the Score property

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

In the GET method, initialize and populate your view model and pass it to the view

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
}

这篇关于我如何在MVC中的Post上获取许多文本框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆