How to put a file upload button optional in asp.net c# applications?










2















I have a basic asp.net c# application which has a form to submit some data to database, This form has an upload button to upload a file.



Initially, there was a problem that: i was not able to submit a form without uploading a file, it was giving an error as [object reference not set to an instance of an object], which means uploading a file was a must before submitting the form, So to resolve that issue i made some changes in my controller.



Now it submits the form even if i don't upload anything, but the new problem is that when i upload a file and submit then it still submits the form successfully but it does not upload the actual file.



This is the model:



 public class Events

public int Id get; set;
public string title get; set;
public string amount get; set;
public string Finance_Approval get; set;
public DateTime date_time get; set;

public string file_one get; set;
[NotMapped]
public HttpPostedFileBase file1 get; set;



This is the controller:



 public ActionResult Index()

return View();



public ActionResult Request(Events e)

if (e.file_one==null)

_context.evt.Add(e);
_context.SaveChanges();

return Content("Added");


else

string filename = Path.GetFileNameWithoutExtension(e.file1.FileName);
string extension = Path.GetExtension(e.file1.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
e.file_one = "PM_Files/" + filename;
filename = Path.Combine(Server.MapPath("~/PM_Files/"), filename);
e.file1.SaveAs(filename);

_context.evt.Add(e);
_context.SaveChanges();

return Content("Added");





And this is the razor view:



@using (Html.BeginForm("Request", "Requester", FormMethod.Post, new enctype = "multipart/form-data" ))

<div class="form-group">
@Html.LabelFor(a => a.title)
@Html.TextBoxFor(a => a.title, new @class = "form-control" )
</div>
<div class="form-group">
@Html.LabelFor(a => a.amount)
@Html.TextBoxFor(a => a.amount, new @class = "form-control" )
</div>
<div class="form-group">
<label>Select the file word or pdf etc</label>
<input type="file" name="file1" />
</div>
<button class="btn btn-primary">Request</button>










share|improve this question



















  • 1





    Your file is being uploaded, but you do not have a form control for file_one so its always null - you else block will never be executed

    – user3559349
    Nov 14 '18 at 4:52











  • You need this one: @Html.TextBoxFor(a => a.file_one, new @class = "form-control", @readonly = "readonly" ) to store the file name. In your current code this textbox doesn't exist, hence the filename is never captured.

    – Tetsuya Yamamoto
    Nov 14 '18 at 4:55











  • @StephenMuecke you mean to say that i have to add the form-control class in upload button and it will resolve the issue

    – John Kamaal
    Nov 14 '18 at 4:56











  • No. You do not have a <input> element for file_one (nor should you). What you need to check is if e.file1 is null, not e.file_one` (and you also check the ContentLength)

    – user3559349
    Nov 14 '18 at 4:59











  • if (e.file_one==null) => this is your problem, because you're checking against file_one string. You should check against file existence, i.e. HttpPostedFileBase.

    – Tetsuya Yamamoto
    Nov 14 '18 at 4:59















2















I have a basic asp.net c# application which has a form to submit some data to database, This form has an upload button to upload a file.



Initially, there was a problem that: i was not able to submit a form without uploading a file, it was giving an error as [object reference not set to an instance of an object], which means uploading a file was a must before submitting the form, So to resolve that issue i made some changes in my controller.



Now it submits the form even if i don't upload anything, but the new problem is that when i upload a file and submit then it still submits the form successfully but it does not upload the actual file.



This is the model:



 public class Events

public int Id get; set;
public string title get; set;
public string amount get; set;
public string Finance_Approval get; set;
public DateTime date_time get; set;

public string file_one get; set;
[NotMapped]
public HttpPostedFileBase file1 get; set;



This is the controller:



 public ActionResult Index()

return View();



public ActionResult Request(Events e)

if (e.file_one==null)

_context.evt.Add(e);
_context.SaveChanges();

return Content("Added");


else

string filename = Path.GetFileNameWithoutExtension(e.file1.FileName);
string extension = Path.GetExtension(e.file1.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
e.file_one = "PM_Files/" + filename;
filename = Path.Combine(Server.MapPath("~/PM_Files/"), filename);
e.file1.SaveAs(filename);

_context.evt.Add(e);
_context.SaveChanges();

return Content("Added");





And this is the razor view:



@using (Html.BeginForm("Request", "Requester", FormMethod.Post, new enctype = "multipart/form-data" ))

<div class="form-group">
@Html.LabelFor(a => a.title)
@Html.TextBoxFor(a => a.title, new @class = "form-control" )
</div>
<div class="form-group">
@Html.LabelFor(a => a.amount)
@Html.TextBoxFor(a => a.amount, new @class = "form-control" )
</div>
<div class="form-group">
<label>Select the file word or pdf etc</label>
<input type="file" name="file1" />
</div>
<button class="btn btn-primary">Request</button>










share|improve this question



















  • 1





    Your file is being uploaded, but you do not have a form control for file_one so its always null - you else block will never be executed

    – user3559349
    Nov 14 '18 at 4:52











  • You need this one: @Html.TextBoxFor(a => a.file_one, new @class = "form-control", @readonly = "readonly" ) to store the file name. In your current code this textbox doesn't exist, hence the filename is never captured.

    – Tetsuya Yamamoto
    Nov 14 '18 at 4:55











  • @StephenMuecke you mean to say that i have to add the form-control class in upload button and it will resolve the issue

    – John Kamaal
    Nov 14 '18 at 4:56











  • No. You do not have a <input> element for file_one (nor should you). What you need to check is if e.file1 is null, not e.file_one` (and you also check the ContentLength)

    – user3559349
    Nov 14 '18 at 4:59











  • if (e.file_one==null) => this is your problem, because you're checking against file_one string. You should check against file existence, i.e. HttpPostedFileBase.

    – Tetsuya Yamamoto
    Nov 14 '18 at 4:59













2












2








2








I have a basic asp.net c# application which has a form to submit some data to database, This form has an upload button to upload a file.



Initially, there was a problem that: i was not able to submit a form without uploading a file, it was giving an error as [object reference not set to an instance of an object], which means uploading a file was a must before submitting the form, So to resolve that issue i made some changes in my controller.



Now it submits the form even if i don't upload anything, but the new problem is that when i upload a file and submit then it still submits the form successfully but it does not upload the actual file.



This is the model:



 public class Events

public int Id get; set;
public string title get; set;
public string amount get; set;
public string Finance_Approval get; set;
public DateTime date_time get; set;

public string file_one get; set;
[NotMapped]
public HttpPostedFileBase file1 get; set;



This is the controller:



 public ActionResult Index()

return View();



public ActionResult Request(Events e)

if (e.file_one==null)

_context.evt.Add(e);
_context.SaveChanges();

return Content("Added");


else

string filename = Path.GetFileNameWithoutExtension(e.file1.FileName);
string extension = Path.GetExtension(e.file1.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
e.file_one = "PM_Files/" + filename;
filename = Path.Combine(Server.MapPath("~/PM_Files/"), filename);
e.file1.SaveAs(filename);

_context.evt.Add(e);
_context.SaveChanges();

return Content("Added");





And this is the razor view:



@using (Html.BeginForm("Request", "Requester", FormMethod.Post, new enctype = "multipart/form-data" ))

<div class="form-group">
@Html.LabelFor(a => a.title)
@Html.TextBoxFor(a => a.title, new @class = "form-control" )
</div>
<div class="form-group">
@Html.LabelFor(a => a.amount)
@Html.TextBoxFor(a => a.amount, new @class = "form-control" )
</div>
<div class="form-group">
<label>Select the file word or pdf etc</label>
<input type="file" name="file1" />
</div>
<button class="btn btn-primary">Request</button>










share|improve this question
















I have a basic asp.net c# application which has a form to submit some data to database, This form has an upload button to upload a file.



Initially, there was a problem that: i was not able to submit a form without uploading a file, it was giving an error as [object reference not set to an instance of an object], which means uploading a file was a must before submitting the form, So to resolve that issue i made some changes in my controller.



Now it submits the form even if i don't upload anything, but the new problem is that when i upload a file and submit then it still submits the form successfully but it does not upload the actual file.



This is the model:



 public class Events

public int Id get; set;
public string title get; set;
public string amount get; set;
public string Finance_Approval get; set;
public DateTime date_time get; set;

public string file_one get; set;
[NotMapped]
public HttpPostedFileBase file1 get; set;



This is the controller:



 public ActionResult Index()

return View();



public ActionResult Request(Events e)

if (e.file_one==null)

_context.evt.Add(e);
_context.SaveChanges();

return Content("Added");


else

string filename = Path.GetFileNameWithoutExtension(e.file1.FileName);
string extension = Path.GetExtension(e.file1.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
e.file_one = "PM_Files/" + filename;
filename = Path.Combine(Server.MapPath("~/PM_Files/"), filename);
e.file1.SaveAs(filename);

_context.evt.Add(e);
_context.SaveChanges();

return Content("Added");





And this is the razor view:



@using (Html.BeginForm("Request", "Requester", FormMethod.Post, new enctype = "multipart/form-data" ))

<div class="form-group">
@Html.LabelFor(a => a.title)
@Html.TextBoxFor(a => a.title, new @class = "form-control" )
</div>
<div class="form-group">
@Html.LabelFor(a => a.amount)
@Html.TextBoxFor(a => a.amount, new @class = "form-control" )
</div>
<div class="form-group">
<label>Select the file word or pdf etc</label>
<input type="file" name="file1" />
</div>
<button class="btn btn-primary">Request</button>







c# asp.net-mvc button file-upload






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 4:58









Foo

1




1










asked Nov 14 '18 at 4:49









John KamaalJohn Kamaal

545




545







  • 1





    Your file is being uploaded, but you do not have a form control for file_one so its always null - you else block will never be executed

    – user3559349
    Nov 14 '18 at 4:52











  • You need this one: @Html.TextBoxFor(a => a.file_one, new @class = "form-control", @readonly = "readonly" ) to store the file name. In your current code this textbox doesn't exist, hence the filename is never captured.

    – Tetsuya Yamamoto
    Nov 14 '18 at 4:55











  • @StephenMuecke you mean to say that i have to add the form-control class in upload button and it will resolve the issue

    – John Kamaal
    Nov 14 '18 at 4:56











  • No. You do not have a <input> element for file_one (nor should you). What you need to check is if e.file1 is null, not e.file_one` (and you also check the ContentLength)

    – user3559349
    Nov 14 '18 at 4:59











  • if (e.file_one==null) => this is your problem, because you're checking against file_one string. You should check against file existence, i.e. HttpPostedFileBase.

    – Tetsuya Yamamoto
    Nov 14 '18 at 4:59












  • 1





    Your file is being uploaded, but you do not have a form control for file_one so its always null - you else block will never be executed

    – user3559349
    Nov 14 '18 at 4:52











  • You need this one: @Html.TextBoxFor(a => a.file_one, new @class = "form-control", @readonly = "readonly" ) to store the file name. In your current code this textbox doesn't exist, hence the filename is never captured.

    – Tetsuya Yamamoto
    Nov 14 '18 at 4:55











  • @StephenMuecke you mean to say that i have to add the form-control class in upload button and it will resolve the issue

    – John Kamaal
    Nov 14 '18 at 4:56











  • No. You do not have a <input> element for file_one (nor should you). What you need to check is if e.file1 is null, not e.file_one` (and you also check the ContentLength)

    – user3559349
    Nov 14 '18 at 4:59











  • if (e.file_one==null) => this is your problem, because you're checking against file_one string. You should check against file existence, i.e. HttpPostedFileBase.

    – Tetsuya Yamamoto
    Nov 14 '18 at 4:59







1




1





Your file is being uploaded, but you do not have a form control for file_one so its always null - you else block will never be executed

– user3559349
Nov 14 '18 at 4:52





Your file is being uploaded, but you do not have a form control for file_one so its always null - you else block will never be executed

– user3559349
Nov 14 '18 at 4:52













You need this one: @Html.TextBoxFor(a => a.file_one, new @class = "form-control", @readonly = "readonly" ) to store the file name. In your current code this textbox doesn't exist, hence the filename is never captured.

– Tetsuya Yamamoto
Nov 14 '18 at 4:55





You need this one: @Html.TextBoxFor(a => a.file_one, new @class = "form-control", @readonly = "readonly" ) to store the file name. In your current code this textbox doesn't exist, hence the filename is never captured.

– Tetsuya Yamamoto
Nov 14 '18 at 4:55













@StephenMuecke you mean to say that i have to add the form-control class in upload button and it will resolve the issue

– John Kamaal
Nov 14 '18 at 4:56





@StephenMuecke you mean to say that i have to add the form-control class in upload button and it will resolve the issue

– John Kamaal
Nov 14 '18 at 4:56













No. You do not have a <input> element for file_one (nor should you). What you need to check is if e.file1 is null, not e.file_one` (and you also check the ContentLength)

– user3559349
Nov 14 '18 at 4:59





No. You do not have a <input> element for file_one (nor should you). What you need to check is if e.file1 is null, not e.file_one` (and you also check the ContentLength)

– user3559349
Nov 14 '18 at 4:59













if (e.file_one==null) => this is your problem, because you're checking against file_one string. You should check against file existence, i.e. HttpPostedFileBase.

– Tetsuya Yamamoto
Nov 14 '18 at 4:59





if (e.file_one==null) => this is your problem, because you're checking against file_one string. You should check against file existence, i.e. HttpPostedFileBase.

– Tetsuya Yamamoto
Nov 14 '18 at 4:59












1 Answer
1






active

oldest

votes


















1














The exact problem is you're checking null against file_one string property, which always has null value because no form control associated with it inside view page. You should check against HttpPostedFileBase instead:



[HttpPost]
public ActionResult Request(Events e)

if (e.file1 != null && e.file1.ContentLength > 0)

// save the file

return Content("Added");


else

// do something else

return Content("Added");




If standard HttpPostedFileBase check above does not work, you should try Request.Files to get the file info:



[HttpPost]
public ActionResult Request(Events e)

if (Request.Files.Count > 0)

foreach (string files in Request.Files)

if (!string.IsNullOrEmpty(files))

// save the file



return Content("Added");


else

// do something else

return Content("Added");




Notes:



1) The form uses FormMethod.Post, therefore the controller action should use [HttpPost] attribute.



2) [NotMapped] attribute is only used for data models to exclude entity mapping to column in database - it is not used in viewmodels, just remove it.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53293357%2fhow-to-put-a-file-upload-button-optional-in-asp-net-c-sharp-applications%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The exact problem is you're checking null against file_one string property, which always has null value because no form control associated with it inside view page. You should check against HttpPostedFileBase instead:



    [HttpPost]
    public ActionResult Request(Events e)

    if (e.file1 != null && e.file1.ContentLength > 0)

    // save the file

    return Content("Added");


    else

    // do something else

    return Content("Added");




    If standard HttpPostedFileBase check above does not work, you should try Request.Files to get the file info:



    [HttpPost]
    public ActionResult Request(Events e)

    if (Request.Files.Count > 0)

    foreach (string files in Request.Files)

    if (!string.IsNullOrEmpty(files))

    // save the file



    return Content("Added");


    else

    // do something else

    return Content("Added");




    Notes:



    1) The form uses FormMethod.Post, therefore the controller action should use [HttpPost] attribute.



    2) [NotMapped] attribute is only used for data models to exclude entity mapping to column in database - it is not used in viewmodels, just remove it.






    share|improve this answer



























      1














      The exact problem is you're checking null against file_one string property, which always has null value because no form control associated with it inside view page. You should check against HttpPostedFileBase instead:



      [HttpPost]
      public ActionResult Request(Events e)

      if (e.file1 != null && e.file1.ContentLength > 0)

      // save the file

      return Content("Added");


      else

      // do something else

      return Content("Added");




      If standard HttpPostedFileBase check above does not work, you should try Request.Files to get the file info:



      [HttpPost]
      public ActionResult Request(Events e)

      if (Request.Files.Count > 0)

      foreach (string files in Request.Files)

      if (!string.IsNullOrEmpty(files))

      // save the file



      return Content("Added");


      else

      // do something else

      return Content("Added");




      Notes:



      1) The form uses FormMethod.Post, therefore the controller action should use [HttpPost] attribute.



      2) [NotMapped] attribute is only used for data models to exclude entity mapping to column in database - it is not used in viewmodels, just remove it.






      share|improve this answer

























        1












        1








        1







        The exact problem is you're checking null against file_one string property, which always has null value because no form control associated with it inside view page. You should check against HttpPostedFileBase instead:



        [HttpPost]
        public ActionResult Request(Events e)

        if (e.file1 != null && e.file1.ContentLength > 0)

        // save the file

        return Content("Added");


        else

        // do something else

        return Content("Added");




        If standard HttpPostedFileBase check above does not work, you should try Request.Files to get the file info:



        [HttpPost]
        public ActionResult Request(Events e)

        if (Request.Files.Count > 0)

        foreach (string files in Request.Files)

        if (!string.IsNullOrEmpty(files))

        // save the file



        return Content("Added");


        else

        // do something else

        return Content("Added");




        Notes:



        1) The form uses FormMethod.Post, therefore the controller action should use [HttpPost] attribute.



        2) [NotMapped] attribute is only used for data models to exclude entity mapping to column in database - it is not used in viewmodels, just remove it.






        share|improve this answer













        The exact problem is you're checking null against file_one string property, which always has null value because no form control associated with it inside view page. You should check against HttpPostedFileBase instead:



        [HttpPost]
        public ActionResult Request(Events e)

        if (e.file1 != null && e.file1.ContentLength > 0)

        // save the file

        return Content("Added");


        else

        // do something else

        return Content("Added");




        If standard HttpPostedFileBase check above does not work, you should try Request.Files to get the file info:



        [HttpPost]
        public ActionResult Request(Events e)

        if (Request.Files.Count > 0)

        foreach (string files in Request.Files)

        if (!string.IsNullOrEmpty(files))

        // save the file



        return Content("Added");


        else

        // do something else

        return Content("Added");




        Notes:



        1) The form uses FormMethod.Post, therefore the controller action should use [HttpPost] attribute.



        2) [NotMapped] attribute is only used for data models to exclude entity mapping to column in database - it is not used in viewmodels, just remove it.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 5:10









        Tetsuya YamamotoTetsuya Yamamoto

        15.3k42140




        15.3k42140



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53293357%2fhow-to-put-a-file-upload-button-optional-in-asp-net-c-sharp-applications%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            ReactJS Fetched API data displays live - need Data displayed static

            政党