asp.net mvc - Dropdown for Saving Model Not Working -


the code not save value musician entity. i'm using viewbag saving selectlist , displays content database on save null musician.primaryinstrument field when debugging. razor :

<td>                              @html.labelfor(model => model.primaryinstrument, htmlattributes: new { @class = "control-label col-md-2" }) </td> <td>   @html.dropdownlist("instrumentlist") </td> 

controller:

public actionresult edit(string id) {   if (id == null)   {     return new httpstatuscoderesult(httpstatuscode.badrequest);   }   musician musician = (musician)db.contractor.find(id);   if (musician == null)   {     return httpnotfound();   }   viewbag.instrumentlist = new selectlist(db.instrument, "id", "name");   return view(musician); }  [httppost] [validateantiforgerytoken] public actionresult edit(musician musician, httppostedfilebase image) {   if(modelstate.isvalid)   {     if (image != null)     {       uploadimage(musician, image);     }     musician.yearsofexperience = convert.toint16(request["yearsofexperience"]);     musician.createdate = datetime.now;     musician.nextdateavailable = datetime.now;     db.entry(musician).state = entitystate.modified;     db.savechanges();      return redirecttoaction("profile");   }   return view(); } 

instrument model:

    public class instrument {     public int id { get; set; }     public string name { get; set; }       public icollection<musician> musician { get; set; } } 

}

musician model:

  public class musician : contractor {     [display(name="primary instrument")]     public string primaryinstrument { get; set; }      [display(name = "primary genre")]     public string primarygenre { get; set; }      [display(name = "website link")]     public string websitelink { get; set; }      [display(name = "youtube link")]     public string youtubelink { get; set; }      [display(name = "soundcloud link")]     public string soundcloudlink { get; set; }      [display(name = "reverbnation link")]     public string  reverbnationlink { get; set; }      public icollection<instrument> instruments { get; set; } } 

your not binding selected instrument property primaryinstrument. helper should be

@html.dropdownlistfor(m => m.primaryinstrument, (selectlist)viewbag.instrumentlist) 

note bind id property of instrument property primaryinstrument

note if modelstate not valid, need reassign viewbag.instrumentlist property - viewbag.instrumentlist = new selectlist(db.instrument, "id", "name"); before call return view(musician);


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 -