问题
I made a dynamic textarea
's group that are added in DOM
dynamically by using JS
.
Those textarea
's, I want them in the controller
, indeed.
I receive null
values in the model.actionLis
t with that code:
Here is the HTML
generated:
<div class="input_fields_wrap">
<div><textarea class="form-control text-box multi-line" name="model.actionList[1].probleme"></textarea> <textarea class="form-control text-box multi-line" name="model.actionList[1].action"></textarea></div>
<div><textarea class="form-control text-box multi-line" name="model.actionList[2].probleme"></textarea> <textarea class="form-control text-box multi-line" name="model.actionList[2].action"></textarea></div>
<div><textarea class="form-control text-box multi-line" name="model.actionList[3].probleme"></textarea><textarea class="form-control text-box multi-line" name="model.actionList[3].action"></textarea></div>
</div>
By this JS
:
$(wrapper).append('<div>Probleme: <textarea class="form-control text-box multi-line" name="model.actionList[' + x + '].probleme"></textarea> Action: <textarea class="form-control text-box multi-line" name="model.actionList[' + x + '].action"></textarea>@*<a href="#" class="remove_field">Remove</a>*@</div>'); //add input box
Server-side, This is the controller
:
public ActionResult Create(AuditViewModel model)
{...}
This is the famous Viewmodel
part that are interesting here:
public class AuditViewModel
{public List<Actions> actionList { get; set; }}
Finally, this is the Action
class:
public class Actions
{
public string probleme { get; set; }
public string action { get; set; }
}
What is wrong?
Thanks in advance!
回答1:
First of all Indexing starts from 0 and secondly use it like actionList[index].SomePeoperty
as actionList is property of your Model
:
When you write:
@model SomeModel
@Html.TextAreaFor(x=>x.SomeProperty)
it is rendered like:
<textarea name="SomeProperty" id="SomeProperty"></textarea>
it is not rendered like:
<textarea name="model.SomeProperty" id="model.SomeProperty"></textarea>
So try it like below:
<div>
<textarea class="form-control text-box multi-line" name="actionList[0].probleme"></textarea>
<textarea class="form-control text-box multi-line" name="actionList[0].action">
</textarea>
</div>
<div>
<textarea class="form-control text-box multi-line" name="actionList[1].probleme"></textarea>
<textarea class="form-control text-box multi-line" name="actionList[1]action">
</textarea>
</div>
<div>
<textarea class="form-control text-box multi-line" name="actionList[2].probleme"></textarea>
<textarea class="form-control text-box multi-line" name="actionList[2].action">
</textarea>
</div>
来源:https://stackoverflow.com/questions/27062269/model-binding-htmlasp-not-working