c# - MVC Filename property mapped to tag so Filename property = selected filename -
c# - MVC Filename property mapped to <input> tag so Filename property = selected filename -
mvc5 ef6 c#
i have create view image class. image class contains string property "imagepathlocal".
i have next on view, allow user select file upload:
<div class="form-group"> @html.label("select image", htmlattributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <input type="file" name="photo" id="photo" class="btn btn-default" /> @html.validationmessagefor(model => model.imagepathlocal, "", new { @class = "text-danger" }) </div> </div> i have utilize
<input type="file" name="photo" id="photo" class="btn btn-default" /> as there isn't equivalent @html.inputfor(model => model.imagepathlocal... etc. utilize - googling has lead me believe have way (correct me if i'm wrong)
when click submit, modelstate isn't valid, imagepathlocal isn't populated. file sent , can save server (if step on validation).
so question is, how can allow user select file , populate imagepathlocal property name of file they've selected when form submitted, model.imagepathlocal populated , hence modelstate valid?
edit: @ehsan, main reply needed use:
@html.textboxfor(m => m.imagepathlocal, new { type="file", @class="btn btn-default"}) however, wanted populate 2 properties 1 time user selected file. string property, filename, , httppostedfilebase property, file user selected. changed form user selecting httppostedfilebase property:
@html.textboxfor(m => m.image, new { type="file", @class="btn btn-default"}) and hanged property whenever gets set, automatically sets string property:
private httppostedfilebase _image; public httppostedfilebase image { { homecoming _image; } set { _image = value; imagepathlocal = _image.filename; } } this achieves require.
you have utilize overload of textboxfor() takes htmlattributes parameter :
@html.textboxfor(m => m.imagepathlocal, new { type="file", @class="btn btn-default"}) you can utilize input it's name should model property name imagelocalpath this:
<input type="file" name="imagelocalpath" id="imagelocalpath" class="btn btn-default" /> c# asp.net-mvc
Comments
Post a Comment