I have an edit form with @Html.TextAreaFor
controls. I need to have a link 'Add New' which will insert a new @Html.TextAreaFor
control at the end of the current display. Should it be @Html.TextArea
control? If so, how should I fetch the information from newly created controls when I submit the form to save it to the DB?
@model ResourceTemplate
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ResourceTemplate</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ResourcesLabel, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ResourcesLabel, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ResourcesLabel, "", new { @class = "text-danger" })
</div>
</div>
@if (Model.Resources.Count() > 0)
{
<div class="form-group">
@Html.LabelFor(model => model.Resources, htmlAttributes: new { @class = "control-label col-md-2" })
@for (var i = 0; i < Model.Resources.Count(); i++)
{
<div class="col-md-10">
@Html.TextAreaFor(m => m.Resources[i].Text, new { htmlAttributes = new { @class = "form-control", @cols = 80, @rows = 50 } })
@Html.TextAreaFor(m => m.Resources[i].Uri, new { htmlAttributes = new { @class = "form-control", @cols = 80, @rows = 50 } })
</div>
}
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
The
TextAreaFor
helper generates a<textarea>
HTML element with the specified property as the name attribute value. Assuming its a new resource object you are trying to add you can follow this to generate a new resource input:EDIT:
Based on comment, depending on how your partial is being rendered, you need to bind your button click event to the addResource function. This way its bound directly on the element markup but you can find an alternate way to bind it unobtrusively depending on your implementation.