c# - How can I update a MVC model list property first be compiling the list on client -
how can update mvc model list property dynamically when user adds value each time input field on view
my app c# web application , using razor views.
so, model has property called workers of data type list:
public class factory { public list<worker> workers { get; set; } public class worker { public string name { get; set; } } }
and, in razor view have following:
@model app.models. factory <div id="worker" class="form-group"> @html.labelfor(m => m.workers, new { @class = "col-lg-2 control-label" }) <div class="container"> @html.textboxfor(m => m.workers, new { placeholder = "worker name", @class="form-control", id="workerinput"}) </div> </div>
the input @html.textboxfor
should have corresponding button called "add worker". so, when user adds worker , clicks button, name of worker should added list of workers. user can add multiple workers.
how can add each name on client(say 5 names) update model on server?
this sample, might need modify code bit.
<script type="text/javascript"> var workers = new array(); function addworker() { workers.push($("#texttoadd").val()); } function submit() { var postdata = { names: workers }; $.ajaxsettings.traditional = true; $.ajax({ url: '@url.action("addworker", "home")', type: "post", datatype: 'json', data: postdata, success: function () { alert("added"); } }); } </script>
here controls
@html.textboxfor(x => x.texttoadd) @html.dropdownlist("workerlist", items); <input type="button" value="addlocal" onclick="addworker();" /> <input type="button" value="post" onclick="submit();" />
and in controller need add items list. hope helps.
public actionresult addworker(list<string> names) { list<string> strings = new list<string>(); if (session["list"] != null) { strings = (list<string>)session["list"]; } foreach (var s in names) { strings.add(s); } session["list"] = strings; return json(strings); }
Comments
Post a Comment