model binding html:asp not working

纵然是瞬间 提交于 2020-01-06 13:50:29

问题


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.actionList 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!