Wednesday, July 17, 2013

AJAX File Upload in MVC using IFrame

As you may aware via google, the Javascript cannot handle the File content. You cannot submit the File by using Ajax.
There are many solutions and plugIn both free and commercial on the Internet. But those seem not meet to my requirements. What I need is a synchronous upload the file and temporary store in object and display on the screen.

Therefore, the best solution is to use hidden IFrame recommended by many people. I just modify and simplify it to meet my requirements.

The result of below code:


The concepts are:
- Create a normal form for submitting file content with "enctype='multipart/form-data'" , and its target attribute is the IFrame ==> when the form is submit only the IFrame is refreshed (user will not aware of it)
- Handle the IFrame load function, to generate the result on the Partial view

Step 1:  I have a model class PostImageFile











Step 2: In the View

We have Form (file and button), Partial view, and the hidden IFrame.



And we have the script when the "SubmitImage" button is clicked:
-  checked if use has select any file
- Submit the form ==> the action "AttachImage" (in the "Post" controller defined in the Form action) will  executed
- The target of the form is the IFrame ==> after the "AttachImage" is executed, the IFrame will reload
- Thus, script in the $("#iFrameImage").load will run. It will invoke "RefreshImagePartialView" action in the "Post" controller


Step 3: The Partial View

"GetImage" is a action in "Post" controller to render image from byte array.


Step 4: Controller
Now, let take a look in the Post controller.

- AttachImage : get the HttpPostedFileBase from the form and it's converted to Byte Array and stored in the TempData.

- RefreshImagePartialView: is called when the IFram is reload in order to refresh the partial view. It get the list of images from TempData and return to the partial view.

- GetImage: is called in the partial view to render image from the byte array. I used the combination of PostDate and FileName as the key for retrieving the byte array.


Friday, July 5, 2013

SQL Server 2008 login Error: returns 233 or 18456 error codes

Failed to log in SQL Server by using "sa" account.

The error code was 18456 which meant wrong password. But, I did input the right password. (If you are not sure about the password of "sa" , log in as any account which has "SysAdmin" role and change the password for "sa").

Sometimes, I got the error 233 which related to the client protocol. Based on the search results on google, I changed the order of client protocol in Sql Server Configuration Manager by setting TCP/IP before the NamedPipes.

But the above 2 solutions don't solve the problem. Actually, because the "Server Authentication" mode was set to "Window Authentication mode" only, that's why "sa" cannot log in.
So, after changing the authentication mode to "Sql Server and Windows Authentication" mode, it works fine.