c# - ListBox not posting to MVC controller -
i have form have text area's , listbox. other fields in form being posted controller not listbox?
here razor code:
<form method="post" action="/admin/addpost"> @html.validationsummary(true) <div class="form-group"> <label>title</label> <input type="text" class="form-control" name="blogtitle" placeholder="title" value="@model.blogtitle" required> </div> <div class="form-group"> <label>image</label> <input type="text" class="form-control" name="blogimage" value="@model.blogimage" placeholder="image"> </div> <div class="form-group"> <label>description</label> <textarea name="blogdescription">@model.blogdescription</textarea> </div> <div class="form-group"> <label>tags</label> @html.listbox("tags", model.tags, new { @class = "form-control", @name = "tags", @multiple = "multiple" }) </div> <button type="submit" class="btn btn-primary">save</button> </form>
here , post controller:
public actionresult addpost() { var model = new blogmodel { blogtitle = string.empty, blogdescription = string.empty, blogimage = string.empty, tags = new tagqueries().getalltags().select(x => new selectlistitem { text = x.tagname, value = x.tagid.tostring(), selected = false }) }; return view(model); } [httppost] public actionresult addpost(blogmodel model) { transferblogdetailstodbmodel addtodb = new transferblogdetailstodbmodel(); if (modelstate.isvalid && model != null) { try { addtodb.transferblogdetails(model); return redirecttoaction("index", "admin"); } catch (exception) { modelstate.addmodelerror("", "invalid data,please try again"); } } return view(model); }
here model:
public class blogmodel { [hiddeninput] public int blogid { get; set; } [required(errormessage = "blog title required")] public string blogtitle { get; set; } [required(errormessage = "blog description required")] public string blogdescription { get; set; } public string blogimage { get; set; } public ienumerable<selectlistitem> tags { get; set; } }
any suggestions appreciated.
your property tags
typeof ienumerable<selectlistitem>
, cannot bind <select multiple>
collection of complex objects. <select>
posts array of simple values (the values of selected options).
your model needs property bind to, say
public ienumerable<int> selectedtags { get; set; }
assuming tagid
of tag
typeof int
. code in view is
@html.listboxfor(m => m.selectedtags , model.tags, new { @class = "form-control" })
side notes:
- do not use
new { @name = "..." }
- fortunately nothing, , never attempt overridename
attribute generatedhtmlhelper
methods - do not use
new { @multiple = "multiple" }
-listbox()
,listboxfor()
methods generate that - use
textboxfor() and
textareafor()` methods generate other form controls correct 2-way model binding - remove
selected = false
code inselectlistitem
constructor (not false default, value ignored anyway - value ofselectedtags
determines selected)
Comments
Post a Comment