Tuesday, July 30, 2013

What Is MVC3 Partial View And Display Partial View On Conditional Bases

In this article i will give small description about mvc partial view and i will give a small example how you can load partial view based on condition.

In MVC Partial view act  as a container. It is used for displaying the information on conditional bases. 

So for this first create mvc3 web application and add a controller . In your controller add the below code.


 public ActionResult Index()
        {
            return View();
        }

Now create the index view. Now in your view add the below code.

@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "Home"))
{
<select name="partialview">
    <option value="1">Partial View 1</option>
    <option value="2">Partial View 2</option>
</select>
    <br /><br />
    <input type="submit" value="Submit" />
    if (ViewBag.Page == "1")
    {
         @Html.Partial("PartialView1");
    }
    else if (ViewBag.Page == "2")
    {
         @Html.Partial("PartialView2");
    }
    }


In above code i have created dropdown in which i have defined the partial view name.
Now we will add two partial view. For this right click on the home view folder and click on add View .

add partial view

As you click on the view option below window will open.

add partial view

By clinking on the "create as partial view" you will be able to crate partial view. In same way create second partial view.

Now add the below code in partial view.

Partial View 1:

<h3>Partial View 1 Loadded Successfully</h3>


Partial View 2:

<h3>Partial View 2 Loadded Successfully</h3>


Now put the below code to complete the controller code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Partialview.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string partialview)
        {
            if (partialview == "1")
            {
                ViewBag.Page = "1";
            }
            else if (partialview == "2")
            {
                ViewBag.Page = "2";
            }
            return View();
        }

    }
}


Now put the break point on the index post method and run the application.



Now click on the button you will hit the break point.

break point

Here you will get the selected value and you according to value will get stored in the viewbag. accordingly it on view partial view will load.

partial view

partial view

How to use CheckboxList In MVC3 View And Get The Checked Items Passed To The Controller with example

In this article i will show you how you can create a checkboxlist in mvc3 and how you can get it`s selected value in controller.

So here we go. first you needed to create a new asp.net mvc3 application. in this add a new controller and model file.
Now create view for the index method of the controller. Now come o your model and add the below code in your model file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC_checkboclist.Models
{
    public class ItemViewModel
    {
        public List<ItemView> ItemViewDataModel { get; set; }
    }
    public class ItemView
    {
        public string Id { get; set; }
        public string CountryName { get; set; }
        public bool Checked { get; set; }
    }
}


Now again come to your controller and add the below code in the controller file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_checkboclist.Models;

namespace MVC_checkboclist.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Hom/

        public ActionResult Index()
        {
            ItemViewModel objitemviewmodel = new ItemViewModel();
            objitemviewmodel.ItemViewDataModel = new List<ItemView>();
            objitemviewmodel.ItemViewDataModel.Add(new ItemView { Id = "1", Checked = true, CountryName = "India" });
            objitemviewmodel.ItemViewDataModel.Add(new ItemView { Id = "2", Checked = false, CountryName = "Pakistan" });
            objitemviewmodel.ItemViewDataModel.Add(new ItemView { Id = "3", Checked = true, CountryName = "Nepal" });
            return View(objitemviewmodel);
        }
        [HttpPost]
        public ActionResult Index(ItemViewModel objitemviewmodel)
        {
          
            string message = "You have selected :";
            foreach (var data in objitemviewmodel.ItemViewDataModel)
            {
                if (data.Checked == true)
                {
                    message += data.CountryName + ",";
                }
            }
            ViewBag.SelectedData = message;
            return View(objitemviewmodel);
        }
    }
}


In above code first i have created httpget method for index. In htis i have created a list of country. In httppost method i have stored the  recived collection value in viewbag.

Now come to view and add the below code. 
@model MVC_checkboclist.Models.ItemViewModel
@using (Html.BeginForm("Index", "Home"))
{
    <h3>
        Getting Checkbox value in controller</h3>
    for (var i = 0; i < Model.ItemViewDataModel.Count; i++)
    {
        @Html.HiddenFor(m => m.ItemViewDataModel[i].Id)
        @Html.HiddenFor(m => m.ItemViewDataModel[i].CountryName)           
        @Html.CheckBoxFor(m => m.ItemViewDataModel[i].Checked)
        @Html.DisplayFor(m => m.ItemViewDataModel[i].CountryName)
    <br />
    }
    <input type="submit" value="Submit" />
    <div><b>@ViewBag.SelectedData</b></div>   
}


Here we are creating the check box list.

now put a break point on the httppost method of the index method of controller and run the application. In out put you will see the item whose checked value was true were in checked condition.

mvc checkboxlist

Now click on submit button your break point will hit and you will get the collection in controller.



Now store the information in view bag. Here is the final output.

mvc checkboxlist

How To Dynamically Add Rows To A Table In MVC3 with Example

In this article i will show you how you can dynamically add rows to a table in MVC3.Like dynamically adding rows in a gridview.

So for this first you needed to create a new mvc3 web application. In this add new controller and a model. After adding model file we will create a model .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace dunamicrows.Models
{
public class StudentModel
{
public List<Detail> DetailModel { get; set; }
}
public class Detail
{
public int RollNo { get; set; }
public string Name { get; set; }
public int Marks { get; set; }
public string Address { get; set; }
}
}


Now come to your controller and generate a view. After generating view add the bellow code in your view.
@model dunamicrows.Models.StudentModel
@{
ViewBag.Title = "How To Dynamically Add Rows To A Table In MVC3 ";
}
< script language="javascript">
function ValidateData() {
if ($(".validateClassRollNo").attr(`value`) == "0" || $(".validateClassRollNo").attr(`value`) == "") {
alert("Please enter a valid Roll No.");
return false;
}else if ($(".validateClassName").attr(`value`) == "" ) {
alert("Please enter name.");
return false;
} else if ($(".validateClassMarks").attr(`value`) == "") {
alert("Please enter marks.");
return false;
} else if ($(".validateClassAddress").attr(`value`) == "") {
alert("Please enter address.");
return false;
}
return true;
}
< /script>
@using (Html.BeginForm("Index", "Home"))
{
<table width="20%" cellpadding="3" cellspacing="0" border="1" style="border-color:Black;border-collapse:collapse;">
<tr style="font-weight:bold;background-color:Gray;height:20px;">
<td>RollNo</td>
<td>Name</td>
<td>Marks</td>
<td>Address</td>
</tr>
@for(int i=0;i<Model.DetailModel.Count;i++)
{
<tr>
< td>@Html.TextBoxFor(m => m.DetailModel[i].RollNo, new { @class = "validateClassRollNo" })</td>
< td>@Html.TextBoxFor(m => m.DetailModel[i].Name, new { @class = "validateClassName" })</td>
< td>@Html.TextBoxFor(m => m.DetailModel[i].Marks, new { @class = "validateClassMarks" })</td>
< td>@Html.TextBoxFor(m => m.DetailModel[i].Address, new { @class = "validateClassAddress" })</td>
</tr>
}
<tr>
< td colspan="4"><input type="submit" value="Add New Record" title="Add New Record" onclick="javascript:return ValidateData();"/></td>
</tr>
</table>
}


`
After this come to your controller and add the below code. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using dunamicrows.Models;

namespace dunamicrows.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/

public ActionResult Index()
{
StudentModel objstudentmodel = new StudentModel();
objstudentmodel.DetailModel = new List<Detail>();
objstudentmodel.DetailModel.Add(new Detail { RollNo = 0, Name = "", Marks = 0, Address = "" });
return View(objstudentmodel);
}
[HttpPost]
public ActionResult Index(StudentModel objstudentmodel)
{
objstudentmodel.DetailModel.Add(new Detail { RollNo = 0, Name = "", Marks = 0, Address = "" });
return View(objstudentmodel);
}

}
}


In above code first i have created index [httpget] methos and after that i have created [httppost] method. In httppost index method i have added one more row in the collection which i am getting after after page post.

Now check the javascript code which i have written in index view page.
<script language="javascript">
function ValidateData() {
if ($(".validateClassRollNo").attr(`value`) == "0" || $(".validateClassRollNo").attr(`value`) == "") {
alert("Please enter a valid Roll No.");
return false;
}else if ($(".validateClassName").attr(`value`) == "" ) {
alert("Please enter name.");
return false;
} else if ($(".validateClassMarks").attr(`value`) == "") {
alert("Please enter marks.");
return false;
} else if ($(".validateClassAddress").attr(`value`) == "") {
alert("Please enter address.");
return false;
}
return true;
}
< /script>


in above code i am validating weather the user have added all the necessary value in newly generated column or not.

Now run the page you will get the output.
dynamic table

Now without adding any data click on the button to ad the row . You will get the error message to fill the details.

alertmessage

Now add the record and click on button

dynamic table

How to Use Country/State/City in MVC3 Cascading DropdownList Using Jquery with Example

 
In this article i will show you how you can create a cascading dropdown list using jquery
in mvc3 application.In this i have used asp.net mvc and jquery.

Here is the article in which i have shown how you can retrieve value of cascaded drop down list in mvc3 in controller
So for this first you needed to create a new mvc3 application. add a controller and a model class file. Now in your model file add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Cascadded_ddl.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}


Here i have created a class for state and city. in country model class i have added all the other classes. Here public SelectList FilteredCity { get; set; } i have used for passing the value after storing in it when user make an Ajax request.

Now come to your controller and add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cascadded_ddl.Models;
namespace Cascadded_ddl.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }
        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStaeId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }
    }
}

In above code i have made the collection for city and state. The below code is used for making the ajax call.
//Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStaeId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }

Now create a view for index action result, and add the below code.
@model Cascadded_ddl.Models.CountryModel
@{
    ViewBag.Title = "Index";
}
<script language="javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value=`0`> Please wait...</option>";
        $(`#ddlcity`).html(procemessage).show();
        var url = "/Home/GetCityByStaeId/";
    
        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value=`0`>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $(`#ddlcity`).html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
    MVC3 Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm("", ""))
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">
    </select>

}

Here is the jquery code which i have used for making ajax call in change event of the state ddl.
<script language="javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value=`0`> Please wait...</option>";
        $(`#ddlcity`).html(procemessage).show();
        var url = "/Home/GetCityByStaeId/";
    
        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value=`0`>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $(`#ddlcity`).html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>


Here i have used the   var url = "/Home/GetCityByStaeId/"; in this Home is the controller name and GetCityByStaeId is the actionresult method in controller.

The below mention piece of code is responsible for showing the please wait message until the response from server not get finish
  var procemessage = "<option value=`0`> Please wait...</option>";
        $(`#ddlcity`).html(procemessage).show();


Now run the application.
MVC3 Cascading Dropdown List

Now select the state

MVC3 Cascading Dropdown List

Her please wait message will come until the processing not get completed .

Here our controller is called. and in parameter we are getting the state id.
MVC3 Cascading Dropdown List

now output

MVC3 Cascading Dropdown List

MVC3 TextBox and DropdownList Validation By Using jQuery UI Validation

In this article i will show you got to use jquery ui validation for validating mvc3 text box and dropdownlist.

So here we go first you needed to create a new mvc3 web application. In this add a model and a controller. In your model file add the below model code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace JqueryValidation.Models
{
    public class StudentModel
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public int Marks { get; set; }
        public List<Section> SectionModel { get; set; }
    }
    public class Section
    {
        public int SectionID { get; set; }
        public string SectionName { get; set; }
    }
}


Now in your controller add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JqueryValidation.Models;

namespace JqueryValidation.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            StudentModel objstudentmodel = new StudentModel();
            objstudentmodel.SectionModel = new List<Section>();
            objstudentmodel.SectionModel.Add(new Section { SectionName = "Section-A", SectionID = 1 });
            objstudentmodel.SectionModel.Add(new Section { SectionName = "Section-B", SectionID = 2 });
            objstudentmodel.SectionModel.Add(new Section { SectionName = "Section-C", SectionID = 3 });
            Section objSection = new Section();
           // objSection.SectionID = null;

            return View(objstudentmodel);
        }
        [HttpPost]
        public ActionResult Index(int id = 0)
        {
            StudentModel objstudentmodel = new StudentModel();
            objstudentmodel.SectionModel = new List<Section>();
            objstudentmodel.SectionModel.Add(new Section { SectionName = "Section-A", SectionID = 1 });
            objstudentmodel.SectionModel.Add(new Section { SectionName = "Section-B", SectionID = 2 });
            objstudentmodel.SectionModel.Add(new Section { SectionName = "Section-C", SectionID = 3 });
            ViewBag.Message = "You have successfully submitted the form.";
            return View(objstudentmodel);
        }

    }
}

In this i have defined the httpget and post method. in http get method i have preparred the list for binding to dropdownlist.
Now create a view for the index and add the below code.
@model JqueryValidation.Models.StudentModel
@{
    ViewBag.Title = "MVC3 TextBox and DropdownList Validation By Using jQuery UI Validation";
}
<link href="../../Styles/ui-lightness/jquery-ui-1.8.13.custom.css" rel="stylesheet" type="text/css" />
<link href="../../Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.13.custom.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.wrapper.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">

    $(document).ready(function () {
        //prepare the validation rules and messages.
        var rules = {
            Name: {
                required: true,
                minlength: 3
            },
            Address: "required",
            Section: { required: true },
            Marks: "required"
        };
        var messages = {
            Name: {
                required: "Please enter name.",
                minlength: "Please enter attleast 3 character for name."
            },
            Address: "Please enter address",
            Section: "Please select student class section.",
            Marks: "Please enter marks"
        };

        // For the validator
        var validatordata
            = new jQueryValidatorWrapper("StudentForm", rules, messages);

        // click event to do the validation
        $("#btnsubmit").click(function () {
            if (!validatordata.validate()) {
                return false;
            } else {
                return true;
            }

        });
    });
      
</script>
<form name="StudentForm" id="StudentForm"  action="/" method="post">
    <table>
    <tr>
    <td colspan="2"><h3></h3></td>
    </tr>
        <tr>
            <td align="right">
                Name:
            </td>
            <td>
                @Html.TextBoxFor(m => m.Name)
            </td>
        </tr>
        <tr>
            <td align="right">
                Address :
            </td>
            <td>
                @Html.TextBoxFor(m => m.Address)
            </td>
        </tr>
        <tr>
            <td align="right">
                Marks:
            </td>
            <td>
                @Html.TextBoxFor(m => m.Marks)
            </td>
        </tr>
        <tr>
            <td align="right">
                Class Section :
            </td>
            <td>
                <select id="ddlsection" name="Section">
                    <option value="" selected="selected">Select Section</option>
                    @foreach (var item in Model.SectionModel)
                    {
                        <option value="@item.SectionID">@item.SectionName</option>
                    }
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" id="btnsubmit" style="width: 100%" value="Submit" />
            </td>
        </tr>
    </table>
    <div style="color:Red;font-weight:bold;">@ViewBag.Message</div>
    </form>


In this i have appllieda trick for preparing the dropdownlist . In htis i have used select list and used or loop for binding the option of the list.  For dropdownlist value for "Select Section" is blank. I have did this because when user will not select the section on that code will get blank and error will occur.

ViewBag.Message i have used so that after postback user will get verified that page have post.

Now we have done . run the application


Now click on the submit button



You will get the error message in jquery ui.

Now fill the form and submit the form.




final outpost after post back

What Is MVC3 Partial View And Display Partial View On Conditional Bases

In this article i will give small description about mvc partial view and i will give a small example how you can load partial view based on condition.

In MVC Partial view act  as a container. It is used for displaying the information on conditional bases. 

So for this first create mvc3 web application and add a controller . In your controller add the below code.


 public ActionResult Index()
        {
            return View();
        }

Now create the index view. Now in your view add the below code.

@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "Home"))
{
<select name="partialview">
    <option value="1">Partial View 1</option>
    <option value="2">Partial View 2</option>
</select>
    <br /><br />
    <input type="submit" value="Submit" />
    if (ViewBag.Page == "1")
    {
         @Html.Partial("PartialView1");
    }
    else if (ViewBag.Page == "2")
    {
         @Html.Partial("PartialView2");
    }
    }


In above code i have created dropdown in which i have defined the partial view name.
Now we will add two partial view. For this right click on the home view folder and click on add View .

add partial view

As you click on the view option below window will open.

add partial view

By clinking on the "create as partial view" you will be able to crate partial view. In same way create second partial view.

Now add the below code in partial view.

Partial View 1:

<h3>Partial View 1 Loadded Successfully</h3>


Partial View 2:

<h3>Partial View 2 Loadded Successfully</h3>


Now put the below code to complete the controller code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Partialview.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string partialview)
        {
            if (partialview == "1")
            {
                ViewBag.Page = "1";
            }
            else if (partialview == "2")
            {
                ViewBag.Page = "2";
            }
            return View();
        }

    }
}


Now put the break point on the index post method and run the application.



Now click on the button you will hit the break point.

break point

Here you will get the selected value and you according to value will get stored in the viewbag. accordingly it on view partial view will load.

partial view

partial view

How to Bind ListBox In MVC3 Razor with Example

In this article i will show you how you can bind a listbox control in mvc application, and how you can get the selected value of the listbox in controller.

So here we go. First you needed to create a new mvc3 application. In this add controller and model. In your model add the below model code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ListBox_In_MVC3.Models
{
    public class CountryModel
    {
        public SelectList CountryList { get; set; }
        public string[] SelectedCountry { get; set; }
    }
    public class Country
    {
        public int Id { get; set; }
        public string CountryName { get; set; }
    }
}


Now in your controller add the below code
public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.CountryList = GetAllCountryList();
            return View(objcountrymodel);
        }

Now prepare the country list 
    public SelectList GetAllCountryList()
        {
            List<Country> objcountry = new List<Country>();
            objcountry.Add(new Country { Id = 1, CountryName = "India" });
            objcountry.Add(new Country { Id = 2, CountryName = "USA" });
            objcountry.Add(new Country { Id = 3, CountryName = "Pakistan" });
            objcountry.Add(new Country { Id = 4, CountryName = "Nepal" });
            SelectList objselectlist = new SelectList(objcountry, "Id", "CountryName");
            return objselectlist;
        }


Now put the post action result method.
[HttpPost]
        public ActionResult Index(CountryModel objcountrymodel)
        {
            objcountrymodel.CountryList = GetAllCountryList();
            //Now we will get the selected name for display
            string SelectedCountryName = "";
            var countrylistname = objcountrymodel.CountryList.Where(m => objcountrymodel.SelectedCountry.Contains(m.Value)).Select(m => m.Text);
            foreach (var item in countrylistname)
            {
                SelectedCountryName += item + ",";
            }
            ViewBag.Country = "Your Selected Country Name "+SelectedCountryName;
            return View(objcountrymodel);
        }

The above action will take  place when page post back take place.  After post back we will get all the value in you model.
CountryModel objcountrymodel.
Now you controller will look as shown below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ListBox_In_MVC3.Models;

namespace ListBox_In_MVC3.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.CountryList = GetAllCountryList();
            return View(objcountrymodel);
        }
        [HttpPost]
        public ActionResult Index(CountryModel objcountrymodel)
        {
            objcountrymodel.CountryList = GetAllCountryList();
            //Now we will get the selected name for display
            string SelectedCountryName = "";
            var countrylistname = objcountrymodel.CountryList.Where(m => objcountrymodel.SelectedCountry.Contains(m.Value)).Select(m => m.Text);
            foreach (var item in countrylistname)
            {
                SelectedCountryName += item + ",";
            }
            ViewBag.Country = "Your Selected Country Name "+SelectedCountryName;
            return View(objcountrymodel);
        }
        public SelectList GetAllCountryList()
        {
            List<Country> objcountry = new List<Country>();
            objcountry.Add(new Country { Id = 1, CountryName = "India" });
            objcountry.Add(new Country { Id = 2, CountryName = "USA" });
            objcountry.Add(new Country { Id = 3, CountryName = "Pakistan" });
            objcountry.Add(new Country { Id = 4, CountryName = "Nepal" });
            SelectList objselectlist = new SelectList(objcountry, "Id", "CountryName");
            return objselectlist;
        }

    }
}


Now create the view for index method and put the below code.
@model ListBox_In_MVC3.Models.CountryModel
@{
    ViewBag.Title = "Index";
}
<h3>
    bind listbox in mvc3 razor</h3>
@using (Html.BeginForm("Index", "Home"))
{
    @Html.ListBoxFor(m => m.SelectedCountry, new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue), new { @Id = "lstcountry", @style = "width:200px;height:60px;" })
    <br /> <input type="submit" value="Submit" title="submit" />
    <div style="color: Red; font-weight: bold;">@ViewBag.Country</div>
}


Now we have done. Now run the application

mvc listbox

Now select the country and click on submit you will get the selected country value in your controller.

mvc listbox


Here is the final output.