Отправить динамически сгенерированную форму в метод действия (с помощью AJAX или отправки формы или любым другим способом)

#javascript #c# #jquery #asp.net-mvc

Вопрос:

Я создал метод действия в представлении и создал динамическую форму, но я не могу отправить метод действия, используя класс модели.

 public class CategoryViewModel
{
    public enum Category
    {
        [Display(Name = "Legal Shield")]
        LegalShield = 1,
        [Display(Name = "Masstort")]
        Masstort = 2,
        [Display(Name = "Workers Compensation")]
        WorkersCompensation = 3,
        [Display(Name = "Motor Vehicle Accident")]
        MVA = 4,
        [Display(Name = "Medical Malpractice")]
        MedicalMalpractice = 5,
        [Display(Name = "Personal Injury")]
        PersonalInjury = 6,
        [Display(Name = "Others")]
        Others = 7
    }
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public int StepCount { get; set; }
    public Category ddrpCategoryId { get; set; }
    public CategoryViewModel()
    {
        CategoryQuestionModels = new List<CategoryQuestionModel>();
    }
   public List<CategoryQuestionModel> CategoryQuestionModels { get;set;}
}

public class CategoryQuestionModel
{
    public string QuestionText { get; set; }
    public CategoryQuestionModel()
    {
        CategoryOptionModels = new List<CategoryOptionModel>();
    }
    //public CategoryOptionModel CategoryOptionModels { get; set; }
    public List<CategoryOptionModel> CategoryOptionModels { get; set; }
}
public class CategoryOptionModel
{
    public string OptionType { get; set; }
    public string labelName { get; set; }
    public string postingValue { get; set; }
    public string fieldName { get; set; }
    public string Actiontype { get; set; }
    public string actiontypeName { get; set; }
    public string Buttonlabel { get; set; }
    public string placeholderName { get; set; }
    public string DispositionName { get; set; }
    public string DispositionId { get; set; }
}
 
 var isInputExists = [];
$(document).ready(function () {

    var tabID = 1;
    var stepCounts;
    $('#btn-add-tab').click(function () {
        stepCounts = parseInt($("#txtStepsCount").val());
        if (stepCounts > 0) {

            $('#tab-list').html('');
            $('#tab-content').html('');

            for (var i = 0; i < stepCounts; i  ) {
                var nxtbtn1;
                if (i == 0) {
                    nxtbtn1 = '<a class="btn btn-primary btnNext" >Next</a>';
                }
                else if (i === (stepCounts - 1)) {
                    nxtbtn1 = '<a class="btn btn-primary btnPrevious" >Previous</a>  <input class="btn btn-success finaltab" type="submit" value="Submit"/>' /*< a class="btn btn-success finaltab" > Submit</a >*/
                }
                else {
                    nxtbtn1 = '<a class="btn btn-primary btnPrevious">Previous</a>    <a class="btn btn-primary btnNext" >Next</a>'
                }

                $('#tab-list').append($('<li><a href="#tab'   i   '" role="tab" data-toggle="tab">Steps '   i   '</a></li>'));

                $('#tab-content').append($('<div class="tab-pane fade" id="tab'   i   '"></br></br> Question Label: <textarea id="CategoryQuestionModels.QuestionText'   i   '" name="CategoryQuestionModels['   i   '].QuestionText" rows="4"'   'cols = "50" ></textarea ></br ></br > '  

                    'Options : <select  id="ddrpCategoryId'   i   '" name="ddrpCategoryId'   i   '">'  

                    '<option value="text">Text Box</option>'  
                    //'<option value="checkbox">CheckBox</option>'  
                    '<option value="radio">Radio Button</option>'  
                    '<option value="button"> Button</option>'  

                    //'<option value="select">Drop Down</option>'  
                    '</br></br></select> <span id="fooBar'   i   '">amp;nbsp;</span>'  

                    '<input type="button" class="btn btn-primary" value="Choose Options" onclick="addOptions('   i   ')"/>'  

                    '</br></br><div id="mainActionTypes'   i   '" hidden></div>'  

                    '</br></br><div class="col-md-10" id="buttonTypes'   i   '" hidden>'  
                    '</div>'  
                    nxtbtn1  
                    '</div>'))
            }
            $('#tab-list').show();
            $('#tab-content').show();

            $('.btnNext').click(function () {
                $('.nav-tabs > .active').next('li').find('a').trigger('click');
            });

            $('.btnPrevious').click(function () {
                $('.nav-tabs > .active').prev('li').find('a').trigger('click');
            });
        }
        else {
            alert("please enter some value ");
        }
    });

    $(document).on('click', '.btn_remove', function () {
        var button_id = $(this).attr("id");
        $('#row'   button_id   '').remove();
    });

    $(document).on('click', '.btntype_remove', function () {
        var button_id = $(this).attr("id");
        $('#rowbtn'   button_id   '').remove();
    });

    $(document).on('click', '.btnrmvDynamic_remove', function () {
        var button_id = $(this).attr("id");
        $('#actionTypes'   button_id   '').remove();

        isInputExists = jQuery.grep(isInputExists, function (value) {
            return value != button_id;
        });
    });

});

function BindDispositionId(id, type, ids) {

    $("#ddlDispositionId_"   type   "_"   id   "_"   ids).empty();
    $.ajax({
        type: 'GET',
        url: "/Category/GetDispositionId",
        dataType: 'json',
        success: function (Dispositions) {
            var DispositionsList = '<option value="">Select Disposition Id</option>';
            for (var i = 0; i < Dispositions.length; i  ) {
                DispositionsList = DispositionsList   '<option value='   Dispositions[i].Value   '>'   Dispositions[i].Text   '</option>';
            }
            $("#ddlDispositionId_"   type   "_"   id   "_"   ids).html(DispositionsList);
        },
        error: function (ex) {
            alert('Failed to retrieve Disposition Id.'   ex);
        }
    });
}

function BindDispositionName(id, type, ids) {

    $("#ddlDispositionName_"   type   "_"   id "_"   ids).empty();
    $.ajax({
        type: 'GET',
        url: "/Category/GetDispositionName",
        dataType: 'json',
        success: function (Dispositions) {
            var DispositionList = '<option value="">Select Disposition Name</option>';
            for (var i = 0; i < Dispositions.length; i  ) {
                DispositionList = DispositionList   '<option value='   Dispositions[i].Value   '>'   Dispositions[i].Text   '</option>';
            }
            $('#ddlDispositionName_'   type   "_"   id   "_"   ids).html(DispositionList);
        },
        error: function (ex) {
            alert('Failed to retrieve Disposition Name.'   ex);
        }
    });
}

function appendDynamicField(id, type) {
    var labelValueName;

    var drpId = $("#ddrpCategoryId"   id).attr('id');

    BindDispositionId(id, type,"");
    BindDispositionName(id, type,"");

    if (type == "text") {
        labelValueName = '<td><input type="text" id="CategoryOptionModels[0].labelName" name="CategoryOptionModels[0].labelName" placeholder="Enter your label" class="form-control labelName_list" /></td><td><input type="text" name="CategoryOptionModels[0].placeholderName" placeholder="Enter your place holder" class="form-control name_placeholder" /></td><td><input type="text" name="CategoryOptionModels[0].fieldName" placeholder="Enter your field Name" class="form-control name_fieldName"/><input type="hidden" id="OptionType'   type   id   '_"  name="CategoryOptionModels[0].OptionType" value="'   type   '"><td><select id="ddlDispositionId_'   type   '_'   id   '_'   '" name="CategoryOptionModels[0].DispositionId"></select></td><td><select id="ddlDispositionName_'   type   '_'   id   '_'   '" name="CategoryOptionModels[0].DispositionName"></select></td></td>';
    }
    else {
        labelValueName = '<td><input type="text" name="CategoryOptionModels[0].labelName" placeholder="Enter your label" class="form-control labelName_list" /></td><td><input type="text" name="CategoryOptionModels[0].postingValue" placeholder="Enter your posting Value" class="form-control name_postingValue" /></td><td><input type="text" name="CategoryOptionModels[0].fieldName" placeholder="Enter your field Name" class="form-control name_fieldName" /></td><td><select name="CategoryOptionModels[0].Actiontype" onchange="addTextOnChange(this,''   id   '',''   type   '',''   ""   '')"><option value="">select action type</option><option value="1">URL</option><option value="2">Continue To Next</option><option value="3">Form End</option></select>   <input id="txt'   type   id   '_" name="actiontypeName[0]" type="text" style="display:none;"/><input type="hidden" id="OptionType'   type   id   '_" name="OptionType[0]" value="'   type   '"></td>';
    }

    $('#mainActionTypes'   id).append('<div class="col-md-10" id="actionTypes'   type   id   '"><div class="form-group" >'  
        '<p>'   type   '</p>'  
        '<form name="add_name" id="add_name'   id   '">'  
        '<table class="table table-bordered table-hover" id="dynamic_field'   type   id   '">'  
        '<tr>'  

        labelValueName  

        '<td><button type="button" name="add" onclick="addMoreActions(''   id   '',''   type   '')" class="btn btn-primary">Add More</button>   <button type="button" name="remove" id="'   type   id   '" class="btn btn-danger btnrmvDynamic_remove">X</button></td>'  
        '</tr>'  
        '</table>'  
        '</form>'  
        '</div></div>');
};

function appendDynamicButton(id, type) {

    $('#mainActionTypes'   id).append('<div class="col-md-10" id="actionTypes'   type   id   '"><div class="form-group" >'  
        '<p>'   type   '</p>'  
        '<form name="add_name" id="add_name'   id   '">'  
        '<table class="table table-bordered table-hover" id="dynamic_field'   type   id   '">'  
        '<tr>'  
        '<td><input type="text" name="CategoryOptionModels[0].Buttonlabel" placeholder="Enter your posting Value" class="form-control Buttonlabel_list" /></td><td><input type="text" name="CategoryOptionModels[0].fieldName" placeholder="Enter your field Name" class="form-control name_fieldName" /></td>'  
        '<td><select name="CategoryOptionModels[0].Actiontype" onchange="addTextOnChange(this,''   id   '',''   type   '',''   ""   '')"><option value="">select action type</option><option value="1">URL</option><option value="2">Continue To Next</option><option value="3">Form End</option></select><input id="txt'   type   id   '_" name="CategoryOptionModels[0].actiontypeName" type="text" style="display:none;"/></td>'  
        '<td><button type="button" name="addButton" onclick="addMoreButtonActions(''   id   '',''   type   '')" class="btn btn-primary">Add More</button>    <button type="button" name="remove" id="'   type   id   '" class="btn btn-danger btnrmvDynamic_remove">X</button></td>'  
        '</tr>'  
        '</table>'  
        '</form>'  
        '</div></div>');
};


var ids = 0;
var ids2 = 0;
function addMoreActions(id, type) {
    var drpId = $("#ddrpCategoryId"   id).attr('id');
    //var type = $("#ddrpCategoryId"   id).val();
    var labelValueName;
    ids  ;
  
    if (type == "text") {
        labelValueName = '<td><input type="text" id="CategoryOptionModels['   ids   '].labelName" name="CategoryOptionModels['   ids   '].labelName" placeholder="Enter your label" class="form-control labelName_list" /></td><td><input type="text" id="CategoryOptionModels['   ids   '].placeholderName" name="CategoryOptionModels['   ids   '].placeholderName" placeholder="Enter your place holder" class="form-control name_placeholder" /></td><td><input type="text" name="CategoryOptionModels['   ids   '].fieldName" placeholder="Enter your field Name" class="form-control name_fieldName" /><input type="hidden" id="OptionType'   type   ids   '_" name="CategoryOptionModels['   ids   '].OptionType" value="'   type   '"></td><td><select id="ddlDispositionId_'   type   '_'   id   '_'   ids   '" name="CategoryOptionModels['   ids   '].DispositionId"></select></td><td><select id="ddlDispositionName_'   type   '_'   id   '_'   ids   '" name="CategoryOptionModels['   ids   '].DispositionName"></select></td>';
    }
    else {
        labelValueName = '<td><input type="text" name="labelName['   ids   ']" placeholder="Enter your label" class="form-control labelName_list" /></td><td><input type="text" name="postingValue['   ids   ']" placeholder="Enter your posting Value" class="form-control name_postingValue" /></td><td><input type="text" name="fieldName['   ids   ']" placeholder="Enter your field Name" class="form-control name_fieldName" /></td><td><select name="Actiontype['   ids   ']" onchange="addTextOnChange(this,''   id   '',''   type   '',''   ids   '')"><option value="">select action type</option><option value="1">URL</option><option value="2">Continue To Next</option><option value="3">Form End</option></select>   <input id="txt'   type   id   '_'   ids   '" name="actiontypeName['   ids   ']" type="text" style="display:none;"/><input type="hidden" id="OptionType'   type   ids   '_" name="OptionType['   ids   ']" value="'   type   '"></td>';
    }

    $('#dynamic_field'   type   id).append('<tr id="row'   type   drpId   ids   '">'  
        labelValueName  
        '<td><button type="button" name="remove" id="'   type   drpId   ids   '" class="btn btn-danger btn_remove">X</button></td ></tr >');
    BindDispositionId(id, type, ids);
    BindDispositionName(id, type, ids);
};

function addMoreButtonActions(id, type) {
    var drpId = $("#ddrpCategoryId"   id).attr('id');
    //var type = $("#ddrpCategoryId"   id).val();
    ids2  ;

    $('#dynamic_field'   type   id).append('<tr id="row'   type   drpId   ids2   '"><td><input type="text" name="CategoryOptionModels['   ids2   '].Buttonlabel" placeholder="Enter your posting Value" class="form-control Buttonlabel_list" /></td><td><input type="text" name="CategoryOptionModels['   ids2   '].fieldName" placeholder="Enter your field Name" class="form-control name_fieldName" /></td>'  
        '<td><select name="CategoryOptionModels['   ids2   '].Actiontype" onchange="addTextOnChange(this,''   id   '',''   type   '',''   ids2   '')"><option value="">select action type</option><option value="1">URL</option><option value="2">Continue To Next</option><option value="3">Form End</option></select><input id="txt'   type   id   '_'   ids2   '" name="CategoryOptionModels['   ids2   '].actiontypeName" type="text" style="display:none;"/></td><td><button type="button" name="remove" id="'   type   drpId   ids2   '" class="btn btn-danger btn_remove">X</button></td></tr>');
};

Array.prototype.containsSubString = function (text) {
    for (var i = 0; i < this.length;   i) {
        if (this[i].toString().indexOf(text) != -1)
            return i;
    }
    return -1;
}

function addOptions(id) {
    var type = $("#ddrpCategoryId"   id).val();
    var newType = type   id;

    if (isInputExists.containsSubString(newType) !== -1) {
        alert("already exists "   type);
    }
    else {

        isInputExists.push(newType);

        if (type.toString() === "radio".toString()) {
            appendDynamicField(id, type);
            $('#mainActionTypes'   id).show();
        }
        else if (type.toString() === "select".toString()) {
            appendDynamicField(id, type);
            $('#mainActionTypes'   id).show();
            //$('#buttonTypes'   id).show();
        }
        else if (type.toString() === "text".toString()) {
            appendDynamicField(id, type);
            $('#mainActionTypes'   id).show();
        }
        else if (type.toString() === "button".toString()) {
            appendDynamicButton(id, type);
            $('#mainActionTypes'   id).show();
        }
        else if (type.toString() === "checkbox".toString()) {
            appendDynamicField(id, type);
            $('#mainActionTypes'   id).show();
        }
    }
}

function addTextOnChange(type, id, catType, dynamicId) {
    var value = type.value;
    $("#txt"   catType   id   "_"   dynamicId).hide();

    if (value == 1) {
        $("#txt"   catType   id   "_"   dynamicId).show();
    }
    else if (value == 2) {
        $("#txt"   catType   id   "_"   dynamicId).show();
    }
    else {
        $("#txt"   catType   id   "_"   dynamicId).hide();
    }
} 
   #tab-list .close {
            margin-left: 7px;
        } 
 @model AdminCategory_BAL.CategoryViewModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Dynamic Question Page</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <style>
        #tab-list .close {
            margin-left: 7px;
        }
    </style>
</head>
<body>
    <div>
        <div class="container">
            <div class="row">
                @using (Html.BeginForm("AddDynamicQuestionOptionstwo", "Category", FormMethod.Post))
                {
                    @Html.AntiForgeryToken()
                    <div class="col-md-12">
                        <p>
                            @Html.EnumDropDownListFor(model => model.ddrpCategoryId, "Select Category")

                            @Html.TextBoxFor(x => x.StepCount, new
                            {@*@class = "form-control",*@  @name = "StepCount",
                            @id = "txtStepsCount"
                        })
                            <button id="btn-add-tab" type="button" class="btn btn-primary pull-right">Add Tab</button>
                        </p>

                        <ul id="tab-list" class="nav nav-tabs" role="tablist" hidden>
                        </ul>

                        <div id="tab-content" class="tab-content" hidden>

                        </div>
                    </div>
                }
            </div>
        </div>
    </div>
</body>

</html>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
<script src="~/Scripts/CategoryTwo.js"></script> 
  public ActionResult AddDynamicQuestionOptionsTwo()
    {
        CategoryViewModel objCategoryViewModel = new CategoryViewModel();
        return View(objCategoryViewModel);
    }

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult AddDynamicQuestionOptionstwo(CategoryViewModel categoryView)
    {

        return View();
    }

    public JsonResult GetDispositionId()
    {
        List<SelectListItem> DispositionIdList = new List<SelectListItem>() {
    new SelectListItem {
        Text = "ASP.NET MVC", Value = "1"
    },
    new SelectListItem {
        Text = "ASP.NET WEB API", Value = "2"
    },
    new SelectListItem {
        Text = "ENTITY FRAMEWORK", Value = "3"
    },
    new SelectListItem {
        Text = "DOCUSIGN", Value = "4"
    },
    new SelectListItem {
        Text = "ORCHARD CMS", Value = "5"
    },
    new SelectListItem {
        Text = "JQUERY", Value = "6"
    },
    new SelectListItem {
        Text = "ZENDESK", Value = "7"
    },
    new SelectListItem {
        Text = "LINQ", Value = "8"
    },
    new SelectListItem {
        Text = "C#", Value = "9"
    },
    new SelectListItem {
        Text = "GOOGLE ANALYTICS", Value = "10"
    },
};
        return Json(DispositionIdList, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetDispositionName()
    {
        List<SelectListItem> DispositionNameList = new List<SelectListItem>() {
        new SelectListItem {
            Text = "ASP.NET MVC", Value = "1"
        },
        new SelectListItem {
            Text = "ASP.NET WEB API", Value = "2"
        },
        new SelectListItem {
            Text = "ENTITY FRAMEWORK", Value = "3"
        },
        new SelectListItem {
            Text = "DOCUSIGN", Value = "4"
        },
        new SelectListItem {
            Text = "ORCHARD CMS", Value = "5"
        },
        new SelectListItem {
            Text = "JQUERY", Value = "6"
        },
        new SelectListItem {
            Text = "ZENDESK", Value = "7"
        },
        new SelectListItem {
            Text = "LINQ", Value = "8"
        },
        new SelectListItem {
            Text = "C#", Value = "9"
        },
        new SelectListItem {
            Text = "GOOGLE ANALYTICS", Value = "10"
        },
};
        return Json(DispositionNameList, JsonRequestBehavior.AllowGet);
    }