Category Archives: in c#

Using viewbag pass data to the view and bind it to my dropdownlist.

In my booking view I has a dropdownlist need bind to my database table, In this tast I just use viewbag. I know it is good habit bind the view to your viewmodel, but sometime you need do some nasty thing to get the job quickly done. So here is the code in my controller to retrive the data and pass it to the viewbag.


here I pass to SelectLists to my view.

I my view you just need this one line of code to get it.

@Html.DropDownList(“SydneySuburb”, null, “Select »”, new { @id = “to_suburb” })

@Html.DropDownList(“SydneySuburb”, null, “Select »”, new {  @id = “from_suburb” })

the dropdown is look like this


Simple isn’t it!!!

First I tried to do this, I search internet, there are expert write it in very complexed way. The expert alway like to write it like that to make them looking like expert( in my view).

here I just figure it out in very simple way.

Have fun!


JQuery Auto complete work with bakcode by using mvc

Recently to convert the new website, I have a bookinng form for the clients to finished the booking,there is some exiting data need to using auto complete. In the past I alway use ajax tool control kits to achieve that result. But now I am kind of fun for JQuery. Here is the Jquery Autocomplete textbox

First I have databses contain all the subuerbs, here is my database table.


here is my action in my BookController:


I let it return json because json is the fast and easy analyse data at moment.

Then in your view , just add the reference to JQuery UI:


You could ignore the timepicker.min.css, and timepicker.min.js, I use it to picker up the time, for autocomplete don’t need those two references.

here just in you view you just need one more line.

@Html.TextBox(“SearhToSuburb”, null, new {type=”text”,@class=”form-control”, @id = “search_to_suburb” })

That’s it. Simply isn’t it. Have fun. Below is what will it looking like.feels

Using two Way Adding “active” tag to your navigation list in an mvc Layout page

Recently my task need convert this website (this is wrote by using classic asp) into MVC.

First I need to create a layout.cshtml for my the new version of this website.Then navigation need add a class named active to it when the action method has been called.

The first way is very simpley, you could wirte a logic to your view, here is one solution:


But the rule of MVC is the view must be simply as possible, I don’t like this nasty and yuck c# code sit in there. So there is a way just by write a CustomHtmlHelpers to improve it.

here is my class file:



Then in your layout page ,your could use it like:


That’s it. By the way, I am using asp mvc4. Hope that could help some one else.

Have fun:)

Basic struction — create Database first ASP MVC Application(Models in three way)

Here in the internet have a lot tutorial introduction about create code first asp mvc application, but in the real life world the database always aready is exsiting. I am not mvc experter, I am fresher now. It took me a while to get the basic struction a while.So I like to write it down wish this could help some people like me struggling in the beginning.

OK, let me asume that we are going to create a online store ecormmerce website.

Way one: basic struction

Then you create a new MVC project through VS2013, first thing is add a connection string to your root web.config file.

It is like this:connectionStr


Models is nothing just class file. You map your table to class file, then when you create a controller you could select strongly type.

finally is the Add one line to Global.asax to stop populater some seed data


See the null meaning don’t popular seed data.

Way two: basic struction(Models is another project)

I won’t talk about the controller or the views. But Models could anything, Web services, WCF and don’t sit in your project, the model is not neccessary sit in your project.So your project only have controller and Views, but the Models is independent. Here is a simple practise I did in my Demo struction is like this:


Way three: basic struction(Model is your entity Framework)


Create marquee news in front page and the news is read from the database with expired data,also included management page to insert news

My boss just saw other company website has a marquee new on the front page, so she asked me if I could make one and arrow her to insert news and the news will dispear at the expired data.

For achieve that task, first I create a table in my database table, here is my table:


then I write a store proceedure, a little tip for fresh guy, alway use store preceedure to insert data for security reasons.


Now, We could start the front end job. I create a user control:marquee.ascx(so you could put it in anyway you like), to display the new, here is my html code:


here is the backcod, I used to open the database and qurery what I need, and bind it to my BulledtedList:


See the code this if(!IsPostBack) is not neccessary, but I use web froms so it wil inherit maintain state so I don’t need retrieve database everytime postback.

here I am also happy to share the css file for style this unorder list to display inline:


A tip for fresh guy, put this in the page your use control will stand it.

Now, you just need drag the usercontrol to any page you want it with this css style in top of the header it. You coud see it.

Then We could start create a page to arrow my boss to insert the bread news, I used boostrap format so it save my time to write css. here is the front page look like:


here is the html code:


The form use jQury Validate, the jquery-ui.js, is for my boss click then will pop up the jQuery calender to arrow her to put the expired date. So simple isn’t, I am love JQure very much, save a lot of time. It remind me when I first time write javascript over 10 years ago, for every simply function I need write a lot codes.

Finally I just need write a event could be fired by this button.


Ok, That’s all. Have fun!

Using c# code to force bootstrap modal stay open after page postback

Recently I write a small function into my application.To enable the driver to input the time the submit the pick up client and drop off the client time.
My boss like the pick up time and drop off time should been populate by just I write a code on the back of page to retrive the time every time the driver click the button.
But the dropoff button driver me to nuts,Because When the dropoff button click I pop out the bootstrap modal.But the problems came out this button need make page postback to retrive the current time and after postback my modal need stay open.
It take me a while to fix out this.
Here is my solution.
first, I need write javascript like this is for to open the modal: #dropoffModal is my hidden modal.

 function openModal() {
$('#dropoffModal').modal({ show: true });

Second I have the the button is like this(See the button click will fire a event named:”Button_DropOff_Click” behind it):


Finally, just write your event on the page behind file:

protected void Button_DropOff_Click(object sender, EventArgs e)
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);

here just a solution. by the way, You could use ScriptManager.RegisterStartupScript() this command call another function in your frond page javascript.

How to create Picture Upload by using ASP MVC 4

This is a very simply example for how to using asp MVC. In this example doesn’t involved with your database. So start from create a model here is your code for your picture upload model. model is cs file, so save below code as PictureModel.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MvcDemo.Models
    public class PictureModel
        public HttpPostedFileBase PictureFile { get; set; }

Then create a action event to your Controller. Controller also just cs file, so save below to one of the Controllers file

//by default, this will be called by get 
public ActionResult PictureUpload()
            return View();

here is the view file code. view is the PictureUpload.cshtml

@model MvcDemo.Models.PictureModel
    ViewBag.Title = "Picture Upload";

Picture Upload

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = “multipart/form-data” })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true)


@Html.LabelFor(model => model.PictureFile)


@Html.TextBoxFor(model => model.PictureFile, new { type = “file” }) @Html.ValidationMessageFor(model => model.PictureFile)

} @section Scripts { @Scripts.Render(“~/bundles/jqueryval”) }

After submit, it will call the post, below is the action event for post

        public ActionResult PictureUpload(PictureModel model)
            if (model.PictureFile.ContentLength > 0)
                var fileName = Path.GetFileName(model.PictureFile.FileName);
                var filePath = Server.MapPath("~/Content/Uploads");
                string savedFileName = Path.Combine(filePath, fileName);
            return View(model);

A store procedure to insert values into multitable without duplicate records

The previous store procedure have records repeated and here is the improve one.

the table like this:



CREATE PROCEDURE [dbo].[spStoreLMStatusRecording]       
@parameterJobID varchar(30),  
@parameterLMStatus nvarchar(10),  
@parameterEntry_datetime datetime   
 @username varchar(500),  
 @Job_Acceptance bit   
    SET @Job_Acceptance = '1'  
 IF NOT EXISTS(SELECT * FROM tblJob where JobID = @parameterJobID)    
  insert into tblJob values(@parameterJobID,@Job_Acceptance);  
  select @username = username from tblUserAuthentication    
  insert into tblLMStatus values(@parameterLMStatus,@parameterEntry_datetime,@parameterJobID,@username)  
  select @username = username from tblUserAuthentication    
  insert into tblLMStatus values(@parameterLMStatus,@parameterEntry_datetime,@parameterJobID,@username)  

Cookies in ASP.NET

Cookies is a small piece of information stored on the client machine. This file is located on client machines “C:\Document and Settings\Currently_Login user\Cookie” path.  Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines. We need to import namespace called  Systen.Web.HttpCookie before we use cookie.
Type of Cookies?

  1. Persist Cookie – A cookie has not have expired time Which is called as Persist Cookie

  2. Non-Persist Cookie – A cookie has expired time Which is called as Non-Persist Cookie

How to create a cookie?
Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie
Example 1:
        HttpCookie userInfo = new HttpCookie(“userInfo”);
        userInfo[“UserName”] = “Annathurai”;
        userInfo[“UserColor”] = “Black”;
        userInfo.Expires.Add(new TimeSpan(0, 1, 0));

Example 2:
        Response.Cookies[“userName”].Value = “Annathurai”;
        Response.Cookies[“userColor”].Value = “Black”;
How to retrieve from cookie?

Its easy way to retrieve cookie value form cookes by help of Request object.
Example 1:
        string User_Name = string.Empty;
        string User_Color = string.Empty;
        User_Name = Request.Cookies[“userName”].Value;
        User_Color = Request.Cookies[“userColor”].Value;

Example 2:
        string User_name = string.Empty;
        string User_color = string.Empty;
        HttpCookie reqCookies = Request.Cookies[“userInfo”];
        if (reqCookies != null)
            User_name = reqCookies[“UserName”].ToString();
            User_color = reqCookies[“UserColor”].ToString();
When we make request from client to web server, the web server process the request and give the lot of information with big pockets  which will have Header information, Metadata, cookies etc., Then repose object can do all the things with browser.

Cookie’s common property:

  1. Domain => Which is used to associate cookies to domain.

  2. Secure  => We can enable secure cookie to set true(HTTPs).

  3. Value    => We can manipulate individual cookie.

  4. Values  => We can manipulate cookies with key/value pair.

  5. Expires => Which is used to set expire date for the cookies.

Advantages of Cookie:

  1. Its clear text so user can able to read it.

  2. We can store user preference information on the client machine.

  3. Its easy way to maintain.

  4. Fast accessing.

Disadvantages of Cookie

  1. If user clear cookie information we can’t get it back.

  2. No security.

  3. Each request will have cookie information with page.

How to clear the cookie information?


  • we can clear cookie information from client machine on cookie folder


  1. To set expires to cookie object
    userInfo.Expires = DateTime.Now.AddHours(1);
    It will clear the cookie with one hour duration.


This article  is copy from some article is very useful, I past it here, so I could use it  when I need it.

How to use the procedure I write it in last post in your web application

In my last post I just create a store procedure to insert data into 2 tables, here is the c# code how do you use it in your project.

I write a event so for anyone need it just change you connection string then will be reuse.

protected void ButtonClick_StoreRecords(string parameterRef, string parameterLM_Booking_Ref,  string parameterLMStatus, DateTime parameterEntry_datetime)
        string CS = ConfigurationManager.ConnectionStrings["youconnectionstringhere"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
            SqlCommand cmd = new SqlCommand("spStoreLMStatusRecording", con);
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter paramRef = new SqlParameter();
            paramRef.ParameterName = "@parameterRef";
            paramRef.Value = parameterRef;

            SqlParameter paramLM_Booking_Ref = new SqlParameter();
            paramLM_Booking_Ref.ParameterName = "@parameterLM_Booking_Ref";
            paramLM_Booking_Ref.Value = parameterLM_Booking_Ref;

            SqlParameter paramLMStatus = new SqlParameter();
            paramLMStatus.ParameterName = "@parameterLMStatus";
            paramLMStatus.Value = parameterLMStatus;

            SqlParameter paramEntry_datetime = new SqlParameter();
            paramEntry_datetime.ParameterName = "@parameterEntry_datetime";
            paramEntry_datetime.Value = parameterEntry_datetime;