asp.net mvc - HttpPost Action get empty Model on button Click -
scenario
i have master/detail page master data on top , detail data loop in table format.
i want id when user clicks on button.
problem
httppost
action in called empty model. want saleid hiddenfield, not fields required
my models
// sales master model public class sales { [required] [display(name = "sale_id")] public long saleid { get; set; } [required] [display(name = "orderdate")] public datetime orderdate { get; set; } [required] [display(name = "name")] public string name { get; set; } } // detail model public class salesdetail { [required] [display(name = "sale_id")] public long saleid { get; set; } [required] [display(name = "pkg_dur")] public int pkgdur { get; set; } [required] [display(name = "m_name")] public string mname { get; set; } [display(name = "price")] public decimal price { get; set; } } // used display data in view public class salesmd { public sales sale = new sales(); public list<salesdetail> detail = new list<salesdetail>(); }
view is
@model namespace.models.salesmd //for showing master data @html.hiddenfor(m => m.sale.saleid) @html.displayfor(m => m.sale.name) @html.displayfor(m => m.sale.orderdate) // showing detail data in table form @foreach (var item in model.detail) { @html.displayfor(modelitem => item.mname) @html.displayfor(modelitem => item.pkgdur) month(s) @html.displayfor(modelitem => item.price) }
controller
public actionresult salesdetail(models.salesmd md)
(here md getting values 0s , null)
remember: want saleid hiddenfield trying saleid md.sale.saleid
zero
finally rendered html of hidden field. have value
<input data-val="true" data-val-number="the field sale_id must number." data-val-required="the sale_id field required." id="sale_saleid" name="sale.saleid" type="hidden" value="2">
when using
[httppost] public actionresult salesdetail(long saleid)
it generating exception
the parameters dictionary contains null entry parameter 'saleid' of non-nullable type 'system.int64' method 'system.web.mvc.actionresult salesdetail(int64)' in 'mak_erp.controllers.makadmincontroller'. optional parameter must reference type, nullable type, or declared optional parameter. parameter name: parameters
solution
finally solved using html.hiddenfor instead of html.displayfor
html.displayfor
, displaying model properties in view. doesn't render input in view. so, obviously, model null, because there's no data collected in view , submitted controller.
you need use html.editorfor
instead.
if need post hidden input controller, why trying bind posted data viewmodel? change action this:
public actionresult salesdetail(long saleid) { }
Comments
Post a Comment