简体   繁体   中英

What is the correct syntax for appending HTML with JS function?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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