6

I would like to add text box dynamically by clicking add button , can delete text box and finally can save the list values from the text boxes . My model class

public class CustModel
{
    public List<Cust> CustList { get; set; }
}

public class Cust
{
    public string Name { get; set; }
}
My controller class


public class HomeController : Controller
    {
        private DB _entities;

        public HomeController()
        {
            _entities = new DbEntities();
        }

        public ActionResult Index()
        {
                return View(_customers);

        }
        [HttpPost]
        public ActionResult Index(CustModel model)
        {
                // save to the database
                return View();

        }
   } 

I want to know .cshtml code . Or any other suggestion to submit list item to the database .

2 Answers 2

10

Here's how I would do it:

In the CustModel, I will change the property to IEnumerable. I will use EditorTemplate for Cust and this will save extra looping.

public class CustModel
{
    public IEnumerable<Cust> CustList { get; set; }
}

My Index.cshtml view is vary simple, I have declared strongly typed model, then in the form I have @Html.EditorFor for Custlist, a button to add new cust, a button to submit and JQuery script to add new cust. Notice that in the jquery I am creating array of controls so that model binder can pick them properly.

Index.cshtml

@model MvcApplication2.Models.CustModel

@{
    ViewBag.Title = "Home Page";
}


@using (Html.BeginForm()) {
    <fieldset>
        <legend></legend>
        <div id="divcust">
            @Html.EditorFor(m=>m.CustList)
        </div>
        <input id="btnAdd"  type="button" value="Add Cust" onclick="AddCust();" />
        <br />
        <br />
        <input type="submit" value="Submit" />
    </fieldset>
}
<script>
    function AddCust() {
        var m = $('#divcust input:last-child').attr('name');
        var index = 0;
        if (m != null && m.length > 0) {
            index = m.split('CustList[')[1].replace('].Name', '');
            index++;
        }

        var html = '<label for=\"CustList_' + index + '__Name\">Name</label>' +
            '<input id=\"CustList_' + index + '__Name\" class=\"text-box single-line\"' +
            ' type=\"text\" value=\"\" name=\"CustList[' + index + '].Name\">';
        $('#divcust').append(html);


    };
</script>

I have added a EditorTemplates folder in my view/home folder and added a view for Cust:

Cust.cshtml

@model MvcApplication2.Models.Cust

@Html.LabelFor(m=>m.Name)
@Html.EditorFor(m=>m.Name)

Everything works fine now, I can add new Custs and post them to save.

enter image description here

If I want to add delete function, I have to be careful to keep integrity of my control array.

Sign up to request clarification or add additional context in comments.

1 Comment

<button onclick="RemoveTextBox(this)">Delete</button>function RemoveTextBox(button) { $(button).parent().remove(); }
0

you can use this code to dyamically generate UI, implement Validation and posting form values to controller which can easily stored into database.

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

            <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js" type="text/javascript"></script>
            <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js" type="text/javascript"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.js" integrity="sha512-8Z5++K1rB3U+USaLKG6oO8uWWBhdYsM3hmdirnOEWp8h2B1aOikj5zBzlXs8QOrvY9OxEnD2QDkbSKKpfqcIWw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

            <fieldset>
                <legend></legend>
                <form id="DemoForm">
                    <div id="divcust" class="container">

                    </div>
                    <br />
                    <br />
                    <div style="margin-left:30px">
                        <button type="button" name="Submit" onclick="SubmitData()" value="Submit" class="btn btn-success">Success</button>
                        <button type="button" name="Cancel" value="Submit" class="btn btn-danger">Cancel</button>
                    </div>
                </form>
            </fieldset>

            <script>

                var substr = {
                    "product": [
                        { "Label": "First Name", "Id": "Name", "type": "text", "Required": "True" },
                        { "Label": "Age", "Id": "Age", "type": "Number", "Required": "True" },
                        { "Label": "Date of Birth", "Id": "DOB", "type": "date", "Required": "True" },
                        { "Label": "Gender", "Id": "Gender", "type": "select", "Required": "True" },
                        { "Label": "Mobile No", "Id": "Mobile_No", "type": "Number", "Required": "True" },
                        { "Label": "Address 1", "Id": "Address1", "type": "text", "Required": "True" },
                        { "Label": "Address 2", "Id": "Address2", "type": "text", "Required": "False" },
                        { "Label": "Address 3", "Id": "Address3", "type": "text", "Required": "False" },

                        { "Label": "City", "Id": "City", "type": "select", "Required": "True" }
                    ],
                    "DropDown": [
                        { "Key": "Select", "Value": "", "ParentId": "Gender" },
                        { "Key": "Male", "Value": "Male", "ParentId": "Gender" },
                        { "Key": "Female", "Value": "Female", "ParentId": "Gender" },

                        { "Key": "Select", "Value": "", "ParentId": "City" },
                        { "Key": "Mumbai", "Value": "Mumbai", "ParentId": "City" },
                        { "Key": "Thane", "Value": "Thane", "ParentId": "City" },
                        { "Key": "Pune", "Value": "Pune", "ParentId": "City" }
                    ]
                }

                $(document).ready(function () {
                    AddCust();
                    CheckValidation();
                });

                function AddCust() {

                    var html = "";

                    for (var i = 0; i < substr.product.length; i++) {
                        if (substr.product[i].type == "select") {

                            var Dropdown_Values = substr.DropDown.filter(function (item) {
                                return item.ParentId == substr.product[i].Id;
                            });

                            var option = "";
                            Dropdown_Values.forEach(function (item) {
                                option = option + '<option \" class=\"form-control\"' + 'value=\"' + item.Value + '\"> ' +
                                    item.Key + ' </option>'
                            })

                            html = html
                                + '<div class="col-xs-4 col-md-4 col-sm-4"> <label for=\"CustList_' + substr.product[i].Id + '__Name\"> ' + substr.product[i].Label + ': <span id=\"Hide_' + substr.product[i].Id + '\" style="color:red" style="display:none" hidden> * </span></label>'
                                + '<select id=\"' + substr.product[i].Id + '\" class=\"form-control\"' + 'name=\"' + substr.product[i].Id + '\"> ' +

                                option

                                + ' </select></div>';
                        }
                        else {
                            html = html
                                + '<div class="col-xs-4 col-md-4 col-sm-4"> <label for=\"CustList_' + substr.product[i].Id + '__Name\"> ' + substr.product[i].Label + ': <span id=\"Hide_' + substr.product[i].Id + '\" style="color:red" style="display:none" hidden> * </span></label>'
                                + '<input id=\"' + substr.product[i].Id + '\" class=\"form-control\"' + ' type=\"'
                                + substr.product[i].type + '\" value=\"\" name=\"' + substr.product[i].Id + '\"> </div>';
                        }
                    }

                    $('#divcust').append(html);
                };

                function SubmitData() {

                    var Required_Input = substr.product.filter(function (item) {
                        return item.Required == "True";
                    });

                    var $inputs = $('#DemoForm :input');

                    var Form_values = {};
                    $inputs.each(function () {
                        Form_values[this.name] = $(this).val();
                    });
                    delete Form_values.Submit;
                    delete Form_values.Cancel;

                    for (var i = 0; i < Required_Input.length; i++) {

                        var filtered_Key = "";
                        var filtered_Values = "";
                        var Required_alert = Required_Input[i].Label;
                        var Field = Required_Input[i].Id;
                        const filteredByKey = Object.fromEntries(Object.entries(Form_values).filter(([key, value]) => key === Field))

                        for (var key in filteredByKey) {
                            filtered_Key = key;
                            filtered_Values = filteredByKey[key];
                        }

                        if (filtered_Key == Required_Input[i].Id) {

                            if (filtered_Values == "") {
                                alert(Required_alert + " is Required ")
                                return false;
                            }
                        }
                    }

                    Save_Data(Form_values);

                }

                function CheckValidation() {
                    var Required_Input = substr.product.filter(function (item) {
                        return item.Required == "True";
                    });

                    for (var i = 0; i < Required_Input.length; i++) {
                        $("#Hide_" + Required_Input[i].Id).show();
                    }
                }

                function Save_Data(Data) {
                    var Common_Set = {};
                    Common_Set.Json_Input = JSON.stringify(Data);
                    $.ajax({
                        url: "/UserMaster/Save_Data",
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(Common_Set),
                        success: function (result) {
                            // when call is sucessfull
                            alert(JSON.stringify(Data))
                            window.location.reload();
                        },
                        error: function (err) {
                            // check the err for error details
                        }
                    });

                }

            </script>

1 Comment

you can use this code to dyamically generate UI, implement Validation and posting form values to controller which can easily stored into database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.