Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, been getting this error when trying to upload files using ajax.beginform in asp.net mvc5 "Object reference not set to an instance of an object"

here's my view

C#
@using (Ajax.BeginForm("submitSchlAd1", "Ministry", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "error" }, new { @id = "schlregdiv", @class = "form-horizontal" }))
            {
                <label for="inputfile" class="col-sm-4 control-label">Admin's Passport</label>
                <input name="ad1file" type="file" onchange="imgdisp(this)" required>
                
                <label for="inputfile" class="col-sm-4 control-label">NOK Passport</label>
                <input name="ad1file" type="file" onchange="imgdispnok(this)" required>

                <button type="submit" class="btn btn-default">Submit</button>
            }


What I have tried:

and here's my controller function
C#
[HttpPost]
        public ActionResult submitSchlAd1(IEnumerable<HttpPostedFileBase> ad1file)
        {
            FormData fd = new FormData();
            
            try
            {
                    foreach (var file in ad1file)
                    {
                        if (file.ContentLength > 0)
                        {
                            string filename = Path.GetFileName(file.FileName);
                            var path = Path.Combine(Server.MapPath("~/Content/UploadImg"), filename);
                            file.SaveAs(path);
                        
                            fd.ad1pass = System.IO.File.ReadAllBytes(path);
                        }
                    }
                    return View("Court");                
            }
            catch (Exception ex)
            {
                return View("Home");
            }
        }


i don't know what i'm doing wrong, please point out to me.

Thanks for every assistance
Posted
Updated 27-May-16 1:37am
Comments
Sergey Alexandrovich Kryukov 26-May-16 18:31pm    
In what line?
—SA
EasyHero 26-May-16 18:36pm    
sorry it's thrown on the "foreach" line in the controller action
Sergey Alexandrovich Kryukov 26-May-16 22:49pm    
Is it in
foreach (var file in ad1file)
?

Not sure your observation is correct; it would mean that ad1file is null.

Anyway, I have you detailed advice in Solution 1, please follow it.

—SA
EasyHero 27-May-16 4:07am    
Yes ad1file is null. Dunno y
Sergey Alexandrovich Kryukov 27-May-16 8:55am    
Congratulations. Problem solved.
Look, use the debugger and write correct code.
—SA

You did not show where the exception with the message "Object reference not set to an instance of an object" is thrown.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferences by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object".

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx,
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx.

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx.

Good luck,
—SA
 
Share this answer
 
Comments
EasyHero 26-May-16 18:38pm    
sorry it's thrown on the "foreach" line in the controller action
Sergey Alexandrovich Kryukov 27-May-16 8:56am    
Very good. I explained everything. Will you accept the answer formally now?
—SA
EasyHero 27-May-16 9:30am    
Sir, your explanation pointed me out to where d problem was and not necessarily solving it. It's still not working even though I know where d problem is
Sergey Alexandrovich Kryukov 27-May-16 9:38am    
Solving a problem is your responsibility. The project is yours, not mine.
If you know the problem and still don't know how to solve it, this is 1) another problem which can be posed separately, 2) the problem is you; no one can fix it except yourself.
—SA
You are getting the error because ad1file object is null.
In order get the files from the Form, you will have to add enctype="multipart/form-data[^] attribute
C#
@using (Ajax.BeginForm("submitSchlAd1", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "error" }, new { @enctype = "multipart/form-data" , @id = "schlregdiv", @class = "form-horizontal" }))
   {
 
Share this answer
 
Comments
EasyHero 27-May-16 4:07am    
Still giving same error
Karthik_Mahalingam 27-May-16 4:21am    
Give unique names to the file controls
<input name="ad1file" type="file" >

<input name="ad1file" type="file" >
You can't upload files via ajax that way, javascript doesn't have access to the file system in order to serialise the data. Google how to upload files using MVC and jQuery, as this is possible if the client has html5, if they don't have html5 you'll need to use a plug-in designed for ajax uploads for older browsers.

If it's just the multiple thing not working, try giving the different inputs different names, or call them "ad1File[0]" and "ad1File[1]"
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900