简体   繁体   English

发布与动态创建的html元素mvc5相关的数据

[英]Posting data associated with dynamically created html elements mvc5

Im developing a mvc5 application. 我正在开发mvc5应用程序。 In a view i dynamically generate html elements(textboxes and dropdownlists) using a returned json result and jquery. 在视图中,我使用返回的json结果和jquery动态生成html元素(文本框和下拉列表)。 Now what i want to do is posting the selected data id's from ddls and entered texts in textboxes to server. 现在,我要执行的操作是将所选数据ID从Dlls发布,并在文本框中输入文本到服务器。 Both id's and texts are saved in database in nvarchar format. ID和文本都以nvarchar格式保存在数据库中。 The number of ddls and textboxes generated dynamically is varying based on json result. 动态生成的ddls和文本框的数量根据json结果而变化。

This is the json result 这是json结果

 var x = db.ItemTemplates.Where(a => a.MainGroupId == mnId).Where(a => a.SubGruopId == sbId).FirstOrDefault();
        var ids = new List<int> { x.Atribute1, x.Atribute2, x.Atribute3, x.Atribute4 };
 var y = db.Atributes.Where(a => ids.Contains(a.AtributeId)).Select(g => new
            {
                Name = g.AtributeName,
                Options = g.atributeDetails.Where(w=>w.AtributeDetailId!=null).Select(z => new 
                {
                    Value=z.AtributeDetailId,
                    Text=z.AtDetailVal
                })
            });

View briefly 简要查看

@using (@Html.BeginForm("Save", "Item"))
{
    @Html.DropDownListFor(a => a.MainGrpId, new SelectList(ViewBag.mnGrpList,      "MainGroupId", "MainGroupName"), " Select a MainGroup", new { Class = "form-  control", title = "", style = "width:175px;height:30px; margin-top:6px;" })

    @Html.DropDownListFor(a => a.SubGrpId, new SelectList(ViewBag.sbGrpList, "SubGroupId", "SubGroupName"), " Select a SubGroup", new { Class = "form-control", title = "", style = "width:175px;height:30px; margin-top:6px;" })

    <div id="ss" class="col-md-6">

    </div>

    <input type="submit" value="Save" class="btn btn-success" /> 

} }

Jquery jQuery的

var ss = $('#ss');
$('#SubGrpId').change(function () {
    $('#ss').empty();
    $.ajax({
        url: '@Url.Action("FillItem", "Item")', // dont hard code your url's
        type: "GET",
        dataType: "JSON",
        data: { MnId: $('#MainGrpId').val(), SbId: $(this).val() }, // pass the selected value
        success: function (y) {
            $.each(y, function (l, u) {
                // add the label
                var name = u.Name;
                var label = $('<label></label>').text(name).attr('for', name);
                ss.append(label);
                if (u.Options.length==0) {
                    // There is only one item and its for generating a textbox
                    var input = $('<input>').attr({ type: 'text', id: name, name: name });
                    ss.append(input);
                } else {
                    // Its a select
                    var select = $('<select></select>').attr({ id: name, name: name });
                    // add each option
                    $.each(u.Options, function (i, option) {
                        select.append($('<option></option>').val(option.Value).text(option.Text));
                    })
                    ss.append(select);
                }
            });
        },
        error: function () {
            alert("something wrong");
        }
    });
});

ItemModel (6 string type properties for ddls selected and textboxes entered values, only few fields of those 6 will be utilized while saving, sequence is not relevant) ItemModel(用于ddls的6个字符串类型属性和输入的文本框值,保存时仅使用这6个字段中的几个字段,顺序不相关)

public class Item
{
    [Key]
    public int ItemId { get; set; }

    public string ItemName { get; set; }

    public int MainGrpId { get; set; }

    public int SubGrpId { get; set; }

    public string Field01 { get; set; }
    public string Field02 { get; set; }
    public string Field03 { get; set; }
    public string Field04 { get; set; }
    public string Field05 { get; set; }
    public string Field06 { get; set; }

 }

ViewModel(incomplete) 视图模型(不完全)

public class ItemViewModel
{
    public int MainGrpId { get; set; }

    public int SubGrpId { get; set; }
}

Could anyone please guide me on how to organize the viewmodel to capture dynamic html elements and how to do the save functionality. 谁能指导我如何组织视图模型以捕获动态html元素以及如何执行保存功能。

The current code is giving the form elements a name attribute equal to the AtributeName property of your query which does not relate to your model. 当前代码为表单元素提供了一个name属性,该name属性等于查询的AtributeName属性,该属性与您的模型无关。 The name attributes need to be name="Field01" , name="Field02" etc. name属性必须为name="Field01"name="Field02"等。

Change you script to 将您的脚本更改为

var ss = $('#ss');
$('#SubGrpId').change(function () {
  $('#ss').empty();
  $.ajax({
    url: '@Url.Action("FillItem", "Item")', // dont hard code your url's
    type: "GET",
    dataType: "JSON",
    data: { MnId: $('#MainGrpId').val(), SbId: $(this).val() },
    success: function (y) {
      $.each(y, function (l, u) {
        // define the name attribute for the form controls
        var name = 'Field0' + (1 + l); // generates Field01, Field02
        // add the label
        var label = u.Name;
        var label = $('<label></label>').text(label).attr('for', name);
        ss.append(label);
        ....

Your form controls will now bind to a POST method which has a parameter Item - eg public ActionResult Edit(Item model) 您的表单控件现在将绑定到具有参数Item的POST方法-例如, public ActionResult Edit(Item model)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM