0

In my Entity Framework .NET MVC app I want to append a new row to a table with JS but I want to be able to do data validation. Therefore I need to use Html.EditorFor.

This is the current JS code:

$("#add_btn").on('click', function (e) {
        var table = $("#element_table");
        var idx = $(table).find("tbody>tr").length;
        var htmlToAppend = `<tr>
                                <td><input name="item.Elements[${idx}].Name" id="Elements[${idx}].Name" /></td>
                                <td><input name="item.Elements[${idx}].Quantity" id="Elements[${idx}].Quantity" /></td>
                            </tr>`;
        $("#element_table").append(htmlToAppend);
    });

I want to have something like this:

var htmlToAppend = `<tr>
                        <td> @Html.EditFor(model => model.Elements[${idx}].Name </td>
                        <td> @Html.EditFor(model => model.Elements[${idx}].Quantity</td>
                    </tr>`

But I can't find the correct syntax.

1 Answer 1

1

you can't use razor without render view.

best way for this problem you can use html code. example:

$('tr#id td:first').append($('<input type="text" id="textfield" name="fieldName" value="your value" />'));

or try it:

pass your item of model to an action with ajax request and create an action then return a partial view:

public ActionResult yourAction(Model model)
{
    return PartialView(model);
}

and insert your razor code in this view:

@Html.EditFor(model => model.Elements[${idx}].Name
@Html.EditFor(model => model.Elements[${idx}].Quantity
Sign up to request clarification or add additional context in comments.

Comments

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.