asp.net mvc - Add to list mvc -


i'm trying add string data list, have null reference exception , don't have idea how fix this.

here home controller:

public actionresult index() {     return view(); }  [httppost] public actionresult index(chatuser model) {     if (modelstate.isvalid)     {         **model.chatgroup.add(model.inputgroups);**  - here excepton      }     return view(model); } 

and index.cshtml:

@model test.models.chatuser @{     viewbag.title = "test"; }  <h2>@viewbag.title.</h2>  @using (html.beginform("index", "home", formmethod.post, new { @class = "form-horizontal", role = "form" })) {     <div class="form-group">         @html.labelfor(m => m.inputgroups, new { @class = "col-md-2 control-label" })         <div class="col-md-10">             @html.textboxfor(m => m.inputgroups, new { @class = "form-control" })             <input type="submit" value="go" class="btn btn-default" />         </div>     </div>   }  @section scripts {     @scripts.render("~/bundles/jqueryval") } 

your form not include controls properties of chatgroup null when post back. need either initialize property in parameterless constructor

public class chatuser {   public chatuser()   {     chatgroup = new list<string>(); // initialize collection   }   ....   public list<string> chatgroup { get; set; } } 

or initialize in post method

[httppost] public actionresult index(chatuser model) {   if (modelstate.isvalid)   {     model.chatgroup = new list<string>(); // initialize collection     model.chatgroup.add(model.inputgroups);   }   return view(model); } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -