The first thing to do would be to ask for specific feedback from the employer. Not all employers will respond to such a request - it may be against policy to say anything other than accepting or rejecting a candidate. Others may be more forthcoming with tips and suggestions.
Since you submitted your own personal code and not a company sample, you should get some other opinions on your code. Code Review Stack Exchange is one option. If you have any friends who are also software developers, they may be able to help too. If you worked on a company-provided problem, you should ask them before giving the code to anyone else as they may not be appreciative of potential solutions to their coding problems posted in public places, even if the solution wasn't up to their standards.
In the future, if you are asked for a code sample, you can ask them if they have anything in particular that they would like to see or a problem that you can solve. Ideally, you would solve this in the technologies that the company uses if you know them, but some companies are more accepting and would look more at general approaches to solving the problem.
If the company doesn't offer problems, you can find examples. You can go to Project Euler, Programming Praxis, TopCoder, or Programming Puzzles and Code Golf Stack Exchange. Create a GitHub repository and spend whatever you think is a reasonable amount of time to develop some samples. What is reasonable depends on you. Since these are public samples, I would follow my advice above - get other people to review and provide feedback.
The notion of a programmer needing a portfolio is common, but it does a huge disservice to individuals. Many jobs involve building proprietary and closed-source software and also 40+ hours/week of effort, leaving little time outside of work to have a personal life yet also build a respectful portfolio. If a company is not willing to respect and understand the nature of propriety software and the need of people to have a work-life balance in the hiring process, that would be a huge red flag about the company culture and how employees are treated.