asp.net mvc - MVC Binding to a transformed property -


i have object class tag {string key; string text;} , object record bind storage table.

class record { [...id & other properties...]     public string name { get; set; } // "firstrecord"     public string tags { get; set; } // "3,4,9" } 

updating name not present problem. have difficulties tags... can see tags property csv of int keys (say {1:".net",2:"java",3:"perl" ...}).

in record's edit view build dictionary available tags:

dictionary<string, string> tags = viewdata["tags"] dictionary<string, string>; [...] <div class="form-group">     <label class="col-md-2 control-label">tags</label>     <div class="col-md-10">         @foreach (var tag in tags)         {             <div class="checkbox-inline">                 <label for="tag_@tag.key">                     <input type="checkbox" id="tag_@tag.key" value="@tag.key" />                     @tag.value                 </label>             </div>         }     </div> </div> 

and have edit post controller, this

// post: records/edit/5 [httppost, validateantiforgerytoken] public async task<iactionresult> edit(string id, [bind("id,name")] record record) {     if (id != record.id) {         return notfound();     }      if (modelstate.isvalid) {         try {             await repository.updatetableentityasync(record);         }         catch (exception) { [...] }          return redirecttoaction("index");     }     return view(record); } 

so, confused if should bind tags, [bind("id,name,tags")], because value should taken checked check-boxes values, concatenated csv ready updated in storage...

if want bind checkbox values string, values of checkbox , set value of model manually. code below reference.

in view, add name property checkbox.

<input type="checkbox" name="tag_@tag.key" id="tag_@tag.key" value="@tag.key" /> 

in action, values of checkbox using request.form.

[httppost, validateantiforgerytoken] public async task<iactionresult> edit(string id, [bind("id,name")] record record) {     if (id != record.id)     {         return notfound();     }      record.tags = "";     foreach (var key in request.form.allkeys)     {         if (key.startswith("tag_"))         {             record.tags += request.form[key] + ",";         }     }     if (record.tags.length > 0)     {         record.tags = record.tags.remove(record.tags.length - 1, 1);     }      if (modelstate.isvalid)     {         try         {             await repository.updatetableentityasync(record);         }         catch (exception)         {         }          return redirecttoaction("index");     }     return view(record); } 

Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -