user2998990
user2998990

Reputation: 980

Add rows dynamically hainf html helper in asp.net mvc

Following is my code which i am using to add new row with the html helpers in each td.

I am making a view of Bill Of Material in my application for which I need to have a structure where there are many children(ingredients) under a main parent(Main Material).

My approach is to have html helpers in the td and with the button click add row and add the children(ingredients).

I am not able to get a new row when i click the button in my following code. Please help and please suggest if there is any other proper approach for getting my Bill Of Material view done.

I am taking reference of this link .

$("#myButton").click(function () {
    debugger;
    // Create elements dynamically
    var newRow = "<tr><td>'@Html.TextBoxFor(x => x.Id, new { @Value = "1" })'</td><td>'@Html.TextBoxFor(x => x.Name, new { @Value = "Abcd" })'</td></tr>";
    alert(newRow);
    // Add the new dynamic row after the last row
    $('#aliasTable tr:last').after(newRow);
});


<h2>Index</h2>

<table id="aliasTable">
    <tr>
        <td>
            @Html.TextBoxFor(Model => Model.Id, new { @Value = "1" })
        </td>

        <td>
            @Html.TextBoxFor(Model => Model.Name, new { @Value = "Abcd" })
        </td>
    </tr>
</table>

<button id="myButton">Add New Row</button>

Upvotes: 3

Views: 2996

Answers (1)

Aravindan
Aravindan

Reputation: 855

Please change your code like below.

Note: The important thing is you need to mention the razer code (Html helpers) in between the single quotation like ('@Html.TextBoxFor(Model => Model.Id') .

If you must need the strongly type means please use the below code.

[HttpGet]
public ActionResult ActionMethodName()
{
    Test testData = new Test();
    testData.Id = 1 // if Id is integet else testData.Id = "1"
    testData.Name = "Abcd"
    return View("ViewName", testData);
}

You need to add the values from your action method only. then the value return to your page automatically.

Then you can use the below code in your java script to return the value.

var newRow = "<tr><td>" + '@Html.TextBoxFor(x => x.Id)' + "</td><td>" + '@Html.TextBoxFor(x => x.Name)' + "</td></tr>";

else if you don't need the strongly type means use the below code

var newRow = '<tr><td><input type="text" value ="1" name ="Id" /><input type="text" value ="1" name ="Name" /></td></tr>';

Upvotes: 2

Related Questions