Category Archives: HTML

HTML

[RESOLVED]Model state still returns false after I make changes as per the required validations.

My Model state still returns false after I make changes as per the  required validations.

 [HttpPost]
        public ActionResult InsertProject(Project project, HttpPostedFileBase ImageFile = null)
        {

            project.RegistrationId = 1;//Testing
            if (ModelState.IsValid)
            {
                if (ImageFile != null)
                {
                    project.ImageType = ImageFile.ContentType;
                    project.Image = new byte[ImageFile.ContentLength];
                    ImageFile.InputStream.Read(project.Image, 0, ImageFile.ContentLength);
                }
                repository.InsertProject(project);
                return RedirectToAction("List");
            }
            
            return View();
        }

This is part of my view

@using (Html.BeginForm("InsertProject", "Project", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    if (ViewData.ModelState.Keys.Any(k => ViewData.ModelState[k].Errors.Count() > 0))
    { 
   <div class="alert alert-warning">@Html.ValidationSummary()</div>
    }

So when user inputs wrong data, validation summary shows up. After making the required changes when user submits the form, the model state is still invalid. I’m pretty new to mvc. Could you please guide me.

Thanks,

Rose

Show also the Project class code. Which validators you have on it? 

 
@OP: I didn’t answer the question, I only asked to show code around Project class. Please unmark my post as an answer, If your problem is solved then you can update the post.

Yes..Show also the Project class code. Which validators you have on it? this will help us to understand the actual reason for Failing your required field. 

[RESOLVED]Unable to get updated cookie value in jquery after ajax call

I have made a simple cart example in mvc. what I’m doing is , after clicking on Add to cart span , I’m calling a Controller Action method.

And then updating the cookie value with Total no of item in cart. but it give me initial value of cookie.

This is my Ajax Code to call Controller Action

$(document).delegate('.addCart','click', function () {
            var getId = parseInt($(this).attr('id').slice(3));
            $.ajax({
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                url: '/Comments/CartDetailsSetGet',
                data: { Id: getId },
                success: function (data) {
                    var count = parseInt(data);
                    if (isNaN(count)){
                        alert(data);
                    }else{
                        var getCookies=  @HttpContext.Current.Request.Cookies["CartCookie"].Value;
                        $('.cartNum').html(getCookies);
                    }
                },
                error: function (data) {
                    alert("Error In Adding Item To Cart");
                }
            });
        });

There is span > with class cartNum in which I’m showing Total no of item in cart .

addCart is span on which I’m Clicking to Add Item In Cart.

This is my Action Method , which is My default Action

GuestbookContext db = new GuestbookContext(); // my DbContxt Class
        HttpCookie ck = new HttpCookie("CartCookie");
        public ActionResult Index()
        {
            if (Request.Cookies["CartCookie"] == null)
            {
                ck.Value = "0";
                Response.SetCookie(ck);
            }
            IList<Comment> commentList = db.Comments.ToList();
            return View(commentList);
        }

This Action Which is getting called On Ajax Request.

static List<int?> CartItemsId = new List<int?>();
        public string CartDetailsSetGet(int? Id)
        {
              if (CartItemsId.Contains(Id) != true)
                {
                    CartItemsId.Add(Id);
                    int getCount = CartItemsId.Count();
                    System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value = getCount.ToString();
                    ck.Expires = DateTime.Now.AddDays(-1);
                    var d = "";
                    if (System.Web.HttpContext.Current.Request.Cookies["CartCookie"] != null)
                    {
                        d = System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value;
                    }
                    return d.ToString();
                }
                else
                {
                    return "This Item Is Already In Cart";
                }
            
        }

Here in d I’m getting updated cookie value but in Ajax Success , this line giving me Initial value, i.e 0.

var getCookies=  @HttpContext.Current.Request.Cookies["CartCookie"].Value;

Your razor code is server-side code, it isn’t running inside the browser.  View the source of your page and you’ll see

success: function (data) {
                    var count = parseInt(data);
                    if (isNaN(count)){
                        alert(data);
                    }else{
                        var getCookies=  0;
                        $('.cartNum').html(getCookies);
                    }
                },

so no matter what happens, getCookies is always going to be 0.  You need to read the data from the document.cookie object

http://www.w3schools.com/js/js_cookies.asp

or return the data as part of your ajax method (either as well as, or instead of the cookie)

return View(new {Comments: commentList, Quantity: ck.Value);

then amend your success code to reflect this change

[RESOLVED]How to pass records between Views?

I have a table of records and a submit button.
How do i Pass those records from one view to another another view while clicking the Submit Button?

Thanks in advance!

From the view, the data goes to the respective controller. That’s the route. From that controller you can server your desired view and pass the data to it as model object.

Using the following in the controller action method:

return View("AnotherView",ModelObject);

How did your table initially populate with records?  Action and View code would be useful

Do you mean view to view or from one controller to another controller? What I get from the question is that on submit you will be calling another page/controller?

If it is controller to another controller then use tempdata. 

How to pass data in ASP.Net MVC app refer below

http://msdn.microsoft.com/en-in/library/dd394711(v=vs.100).aspx

there is no direct passing of data between views. a view is html that is returned to the browser. when that view contains an anchor (link) to request a new html page, data can be passed via the query string. if its a form submit, then the form fields are
passed. MVC’s data binder will bind these field to the action parameters (often a model).

so to pass data from one form to another usually requires a form, and submit. all data must be in a <input>, <select> or <textarea>. to pass a complete object, each property must be written to a form field, or that property will not be in the postback data
(which is a name/value collection).

if you are writing a javascript application, then there are more ways to pass data via ajax or dynamic forms, but thats different

You cannot pass data directly from view to another view on submit

you submit data to action and action returns the view by passing the data

Can you give me any sample code on how to pass list of records from one table to another table?

from html table to html table?

or

db table to db table?

From HTML table to another HTML table

check this

<table id="table1" border="1">
    <tr> <td>ID</td> <td>Name</td></tr>
    <tr> <td>1</td><td>Name1</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
    <tr> <td>2</td><td>Name2</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
    <tr> <td>3</td><td>Name3</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
    <tr> <td>4</td><td>Name4</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
</table>
<br />
<br />
<br />
<table id="table2" border="1"><tr> <td>1</td><td>Name1</td> <td></td></table>

    <script>
        function MoveRow(movebutton) {
            var table2 = document.getElementById("table1");
            var table2 = document.getElementById("table2");
            var rowchecked = movebutton.parentNode.parentNode;
            var rowcheckedClone = rowchecked.cloneNode(true);
            var checked = movebutton.checked;
            var foundIndex = -1;
            rowcheckedClone.deleteCell(0);
            rowcheckedClone.deleteCell(1);

            for (var i = 0; i < table2.rows.length; i++) {
                if (rowcheckedClone.isEqualNode(table2.rows[i])) {
                    foundIndex = i;
                }
            }
            if (checked) {
                if (foundIndex == -1)
                    table2.appendChild(rowcheckedClone);
            }
            else {
                if (foundIndex > -1)
                    table2.deleteRow(foundIndex);
            }
        }
    </script>

[RESOLVED]MVC 4 generate ViewModel from multiple tables

I want to generate ViewModel (contains Teacher Name and list of student’s Names) from multiple tables. Teachers table and Student table.

   Teacher’s model contains  public virtual ICollection<Student> Students { get; set; }

var model = (from x in db.Teachers where x.Email = email select new TeacherVM { Name = x.Name, StudentNames = x.Student.ToList() }).FirstOrDefault()

How do I retrieve all students into the TeacherVM in a format ("Bob","Mike","Dan")

Thanks,

Can you post your Teacher and Student models?

 public class Teachers
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public virtual ICollection<Student> Students { get; set; }
      …..
   }

    public class Student
    {
        public int Id { get; set; }
        public string Name{ get; set; }
        public virtual ICollection<Teachers> Teachers{ get; set; }
        …..
    }

And you want to list all students assigned to a specific teacher?  Or you just want to list all teachers and all students?

all students assigned to a specific teacher

so the viewmodel would contain 2 fields Teacher Name and list of all students

I tried this but I think I am missing something.

var model = (from x in db.Teachers where x.Email = email select new TeacherVM { Name = x.Name, StudentNames = x.Student.ToList() }).FirstOrDefault()

In the view I want to display 2 textboxes first textbox "Teacher Name" and another textbox all students comma separated
Bob,Mike,Dan

Thanks,

Do you have a relationship mapping between Teacher and Student?  Typically when you have a many-to-many relationship schema, you need a 3rd class/model/table that maps the relationship between those tables.  With your current two tables, you don’t have any
way of knowing which student belongs to which teacher, and vice versa.

Example:

public class Enrollment
{
  public int EnrollmentID { get; set; }
  public int TeacherID { get; set; }
  public int StudentID { get; set; }
}

and then you’d need primary keys in your Teacher and Student tables:

    public class Teachers
    {
        public int TeacherID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
      .....
    }

    public class Student
    {
        public int StudentID { get; set; }
        public string Name{ get; set; }
        public virtual ICollection<Enrollment> Enrollments{ get; set; }
        .....
    }

Your Enrollments table would then have data like this:

EnrollmentID TeacherID StudentID
1 1 2
2 1 3
3 2 1
4 2 3

As you can see in the table above, Teacher #1 has Students #2 and #3, while Teacher #2 has Students #1 and #3.  Student #3 has teachers #1 and #2.  This is critical information that we need to have for many-to-many relationships.

Once you have this schema, you can create your Teacher-Students list

Teacher Details action:

public ActionResult TeacherDetails(int id)
{
  var teacher = db.Teachers.Find(id);

  return View(teacher);
}

View:

@model AppName.Models.Teacher

Teacher Name: @Model.Name
Teacher Email: @Model.Email

<h3>Students assigned to Teacher</h3>

@foreach (var item in Model.Enrollments)
{
  @Html.DisplayFor(modelItem => item.Student.Name) <br />
}

And that’s it.  Pretty standard solution for many-to-many relationships.

Thanks John for the explanation all makes sense. I was wondering instead of 

  var teacher = db.Teachers.Find(id);

to add teacher’s record and the student names into viewmodel in the controller

 public class TeacherVM 
    {
       public string Name { get; set; }
       public string StudentNames { get; set; } 
    }

something like this:

var model = (from x in db.Teachers 
             where x.Email = email 
             select new TeacherVM { 
                Name = x.Name,
                StudentNames = ??  <-- not sure how to get the list
             }).FirstOrDefault()
return View("teacher", model)

and then pass the viewmodel into the view so instead of doing a foreach to retrieve each single student.name I would just pass a string that would contain 
Bob,Mike,Dan into the textbox so the that the teacher can update the textbox right away instead of having edit button and another page. I hope it makes sense what I want to do. thanks for your help!

Sorry for the delayed response.  Let’s take a look at why you can’t do it the way you want to.

Yes, you could totally use a view model if you wanted, however you still need a relationship mapping between teacher(s) and student(s).  This is why I suggested a 3rd table (Enrollments) to establish which student has which teacher, and vice versa.

StudentNames = ??  <-- not sure how to get the list

With your current solution (Teacher and Student tables only), you have no way of getting this list.  There’s no association between the two.  Hence, you need that Enrollments table.  If you had that table, you could do something like this:

var teacher = db.Teachers.Single(t => t.Email == email);
var students = db.Students.Where(s => s.Enrollments.TeacherID == teacher.TeacherID); var model = new TeacherVM(); model.Name = teacher.Name; model.StudentNames = string.Join(",", students); return View(model);

As you can see, we use the Enrollments model to track down the students that have the teacher’s ID associated to their record in the Enrollments table.  How ever you want to handle this solution, you need to have a table that manages your many-to-many relationships.

You are absolutely correct. Sorry it took me a while to get this, new to mvc. But you made it all clear. Appreciate your help.

[RESOLVED]How to access a certain model List from a partial VIEW

Hi,

I have defined a model that contains within it, 2 models as such :

    public class TBRModel
    {
        public List<TBModel> TBModel { get; set; }
        public List<TRModel> TRModel { get; set; }
    }

My controller adds to the TBModel and TRModel and then at the end adds to the TBRModel. When i do this in debug mode i see that this is happens correctly.

        [HttpPost]
        public ActionResult OTBHeaderTR(string tID, string taUserName, DateTime tbDate)
        {
            bool exec_sp_success = false;

            ViewBag.userName = SessionBag.Current.UserName;
            ViewBag.userTypeID = SessionBag.Current.userTypeID;

            TempData["frompage"] = TempData["l_frompage"];

            DBController dbcontroller1 = new DBController();

            if (dbcontroller1.DBConnection())
            {
                MySqlCommand command1 = new MySqlCommand("view_tr_header;", dbcontroller1.conn);
                command1.CommandType = System.Data.CommandType.StoredProcedure;

                MySqlCommand command2 = new MySqlCommand("view_user_rate_detail;", dbcontroller1.conn);
                command2.CommandType = System.Data.CommandType.StoredProcedure;

                MySqlCommand command3 = new MySqlCommand("view_tr_min_max_avg;", dbcontroller1.conn);
                command3.CommandType = System.Data.CommandType.StoredProcedure;

                ......................
                .....................

                try
                {
                    MySqlDataReader rdr1 = command1.ExecuteReader();

                    var tbList = new List<TBModel>();

                    var trB = new TBModel();

                    while (rdr1.Read())
                    {
                        trB.tID = (long)(rdr1["tID"]);
                        ...............
                        ...............
                        tbList.Add(trB);
                    }

                    //Close the first SP Call
                    rdr1.Close();
                    exec_sp_success = true;

                    MySqlDataReader rdr2 = command2.ExecuteReader();

                    var tRateList = new List<TRModel>();
                    while (rdr2.Read())
                    {
                        var tComments = new TRModel();
                        tComments.comments = rdr2["vComments"].ToString();
                        tComments.userRate = (Int32)(rdr2["userRate"]);
                        tRateList.Add(tComments);
                    }

                    rdr2.Close();

                    if (exec_sp_success == true)
                    {
                        MySqlDataReader rdr3 = command3.ExecuteReader();

                        while (rdr3.Read())
                        {
                            trB.tMin = (double)(rdr3["trMinB"]);
                            ........
                            .........
                            tbList.Add(trB);
                        }

                        var model = new TBRModel();

                        model.TBModel = tbList;
                        model.TRModel = tRateList;

                        rdr3.Close();
                        dbcontroller1.conn.Close();

                        ViewBag.userName = SessionBag.Current.UserName;
                        TempData["userTypeID"] = SessionBag.Current.userTypeID;
                        return PartialView("_OtherTBDetailTR", model);
                    }
                    else
                    {
                        dbcontroller1.conn.Close();

                        ViewBag.Message = "An Error has occurred. Could not view detail. Please try again or contact the system administrator";
                        return PartialView("_TRError");
                    }
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    dbcontroller1.conn.Close();

                    ViewBag.Message = "Could not view detail. Error " + ex.Number + " has ocurred. Please try again or contact the system administrator.";
                    return PartialView("_TRError");
                }
            }
            else
            {
                ViewBag.Message = "Could not connect to the database. Please try again or contact the system administrator";
                return PartialView("_TRError");
            }
        }

I see the TBRModel contains the 2 models TBModel and TRModel .. By hovering the mouse over TBModel (within TBRModel) i can see 2 TBModels {0} and {1} .. now in my PartialVIEW im trying to do a foreach statement but obviously it is spooling out {0} and {1}
of the TBModels each time im doing a foreach. What i want is to do a foreach on {0} model and then do a separate foreach on {1} TBModel .. I hope this si clear ..

A snippet of my PartialView is :

How do i do this ?

@model grepTravelMVC.Models.TBRModel
      
      @foreach (var item in Model.TBModel)
        {
            <div align="right">
                <font color="#000000" size="2"><b>Total:</b></font>
                <font color="#000000" size="2">@Html.DisplayFor(modelItem => item.Count) |</font>

                <font color="#000000" size="2"><b>Min:</b></font>
                <font color="#000000" size="2">@Html.DisplayFor(modelItem => item.Min) |</font>

                <font color="#000000" size="2"><b>Max:</b></font>
                <font color="#000000" size="2">@Html.DisplayFor(modelItem => item.Max)</font>
            </div>
        }

Thanks Kindly

Naren

I read your post three times and still couldn’t get it.

Try this, move all of your SQL to a Service layer.  Create a folder named Services and put the SQL logic there.  Then for your view create a strongly typed view that has both of the model objects in them before the view is displayed.  

Then tell us what happens…

Hi,

Thanks for the response. For the time being, if you could assist me with the way it is currently structured.

I have created 2 models, TBModel and TRModel and each have their owen set of variables defined. The 3rd model i created has just these 2 models in there. The reason is that i want to be able to use 2 models in my PartialView.

    public class TBRModel
    {
        public List<TBModel> TBModel { get; set; }
        public List<TRModel> TRModel { get; set; }
    }

So, I build my TBModel by calling a stored procedure and return the resultSet of the stored procedure into my Model and add it to a list as such:

tbList.Add(trB)

The above works fine and i do see it being created.

My 2nd stored procedure, returns the resultSet to the first Model and adds to the list of that Model as such:

tbList.Add(trB);

 

I then call another final (3rd) stored procedure, but this time the resultSet goes into another Model and i add it to a new list as such:

tRateList.Add(tComments);

 

I then add these 2 built lists to the 3rd Model i had defined cause the 3rd model contains the other 2, as per below ..

                        var model = new TBRModel();

                        model.TBModel = tbList;
                        model.TRModel = tRateList;

Now, the model.TBModel contains 2 defined Model Structures .. and i can see that during debug mode. One shows TBModel{0} and the other TBModel{1} .. the {0} structure has the returned values of the 1st stored procedure and the {1} contains the resultSet of
the 2nd stored procedure.

So, how do i access the individual {0} and {1} of TBModel ? I want to outout this in my Partial VIEW as defined in my first post. Sorry, i dont know how else to explain this for im not 100% familiar with the .Net terminology. The {0} and {1} is what i see
when im in debug mode, and i got no other way of explaining this.

The data is correct, and im happy with what im returning into the model, however, i just want to be able to access this model that looks like its an array .. ?

Please can you assist

Thanks

Naren

 

If anyone wants to know as to how to combine models into 1 and then use it in a Partial View, this is what ive done. This is a workaround, however, im not sure what the performance impact would be though, if any ..

I have now created 3 models :

  public class TBModel
    {
       public Int64 tID { get; set; }
       ...
    }

    public class TRateModel
    {
	[Display(Name = "User Name")]
          public string taUserName { get; set; }
    }
  
    public class TMMModel
    {
        [Display(Name = "tMB")]
        public double tMB { get; set; }
    }
    
    public class TBRateModel
    {
        public List<TBModel> TBModel { get; set; }
        public List<TRateModel> TRateModel { get; set; }
        public List<TMMModel> TMMModel { get; set; }
    }

I then added the 3 models into 1 model called TBRateModel

In my controller, i created a "LIST" for each model and called my stored procedure which adds to the individual fields in each model.

I then add each list to the TBRateModel as such:

                       var model = new TBRateModel();

                        model.TBModel = trBList;
                        model.TRateModel = trRateList;
                        model.TMMModel = trMMList;

I then just call my Partial View by passing in "model" as a parameter:

return PartialView("_OtherTBDetailTR", model);

In my PartialView I perform the below to access my 3 individual models:

                        @model gTMVC.Models.TBRateModel
                        ....
                        
                        @foreach (var item in Model.TMMModel)
                        {
                           @Html.DisplayFor(modelItem => item.tID)
                           ....
                           ....
                        }
                        
                        @foreach (var item in Model.TBModel)
                        {
                           @Html.DisplayFor(modelItem => item.taUserName)
                           ....
                           ....
                        }

 

[RESOLVED]List<string> passed in ViewBag gets with “System.Collections.Generic.List`1[System.String]”

I have a link to another controller and I want to pass a list of strings.

FirstController.cs

I have list of records in table with checkbox in each row, List of string values are selected by checking the checkbox.

public ActionResult Select(bool isChecked, String id)
        {
            var selectList = (List<String>)HttpContext.Session["SelectList"] ?? new List<String>();
            if (isChecked && !selectList.Contains(id))
            {
                selectList.Add(id);
            }
            else if (!isChecked && selectList.Contains(id))
            {
                selectList.RemoveAll(s => s == id);
            }
            ViewBag.selectList = selectList;
            return Content("OK");
        }

This list of string values i am passing to another SecondController.cs using ‘ViewBag’

public ActionResult AddSitesToUser(string returnUrl,string selectList, int userId = 0)
        {
            ViewBag.selectList = selectList;
}

My View:

(Html.BeginForm("AddSitesToUser", "User", new { returnUrl = ViewBag.returnUrl,selectList=((List<string>)ViewBag.selectList )})

In my FirstController.cs the list of ViewBag.selectList = selectList; created properly, but if i pass those list of strings to SecondController.cs instead of returning list of strings it gives me ‘"System.Collections.Generic.List1[System.String]"

Any idea on what I’m doing wrong?

Thanks

This is because you are using this within the RouteValues parameter of the BeginForm() method, which will populate QueryString variables for the action attribute on the Form itself.

If you are storing a collection of strings within the ViewBag, ASP.NET isn’t going to know how to display this within the URL so it uses "System.Collections.Generic.List" as it was passed a string and that’s the only way it knows how to interpret it.

You might try storing a comma-delimited string within ViewBag which might be able to be passed along more easily as follows :

// When storing your values in the SelectList, consider using a comma-delimited string (e.g. "A,B,C,D,E,F")
ViewBag.selectList = String.Join(",",selectList.Items.Cast<string>().ToArray());

This will add this comma-delimited string to your form properly when it loads your selectList variable : 

(Html.BeginForm("AddSitesToUser", "User", new { returnUrl = ViewBag.returnUrl,selectList=ViewBag.selectList )})

Then when your AddSitesToUser method is posted to, you can pull your collection out of the QueryString and properly split it back into a collection :

public ActionResult AddSitesToUser(string returnUrl,string selectList, int userId = 0)
{
     // Retrieve your list
     List<string> list = selectList.Split(',').ToList();
}

Tried with your solution, but still showing same 

“System.Collections.Generic.List`1[System.String]”

That’s shouldn’t be happening, as the line where you actually set your ViewBag should store a string into it (and not a collection) :

ViewBag.selectList = String.Join(",",selectList.Items.Cast<string>().ToArray());

when you add routes values to the form, ToString() is called on the value to make it a string. for List<> (and most classes). the to string just returns the class name. you need to convert the list to a string value, that your controller can later parse.

[RESOLVED]Prohibit multiple session windows

Hello all,

I have web application and I want prohibit multiple session windows in same browser for same user. Example, user1 is logged in web app via IE. When user open another tab and request some web page which belong to application, it should notify current user
that Multiple Windows are Prohibited.

Please, can you tell me some scenario how I can accomplish this?

Thanks

browsers don’t support this feature. the tabs all share the same session, and look no different from the server.

if this is a real requirement, your only solution is to create a single page application. there would only be 1 html page, and all content would be loaded via ajax. the base page would run a heartbeat to the server via javascript and ajax. a second version
of the page with the same session, would be denied during the heartbeat interval.

[RESOLVED]How to display a default value in Cascading DropDownList using Java Script and MVC4

I have 2 Cascading DropDownLists (State and Cities) .

I populate cities when I select a State.

In the Cities Dropdown list, the default value is not displayed but all the related Cities are displayed.

Can someone please help to populate a default value in Cities Dropdown list?

The following is my model for State and Cities DropDown list

public class AustraliaStates
    {
        [Key]
        [Required]
        public string AustraliaStateId { get; set; }
        [Required]
        public string AustraliaStateName { get; set; }
    }

    public class AustraliaCities
    {
        [Key]
        [Required]
        public string AustraliaCityId { get; set; }

        [Required]
        public string AustraliaCityName { get; set; }
        
        [Required]
        public string AustraliaStateId { get; set; }
        
    }

Accommodation View.cshtml

      <form name="datapluspics" method="post" enctype="multipart/form-data">
                    @Html.ValidationSummary(true)
                    <fieldset>
                    @*Form Display Table START here*@
                    <table class="FormTableStyle" >
                                                
                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.Suburb)
                                </div>
                            </td>
                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    : @Html.EditorFor(model => model.Suburb)
                                    @Html.ValidationMessageFor(model => model.Suburb)
                                </div>
                            </td>    
                        </tr>

                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.State)
                                </div>
                            </td>

                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                            <div>
                                             : @Html.DropDownListFor(model => model.SelectedAustraliaStateId, Model.AustraliaStates, "Select a state", new { id = "States", @class = "DropDownFieldStyle" })
                                             @Html.ValidationMessageFor(model => model.SelectedAustraliaStateId)
                                </div>
                            </td>    
                        </tr>

                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.City)
                                </div>
                            </td>
                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    : @Html.DropDownListFor(model => model.SelectedAustraliaCityId, Model.AustraliaCities, "Select a City", new { id = "Cities", @class = "DropDownFieldStyle" })
                                </div>
                            </td>    
                        </tr>

</table> 
                    </fieldset>
                    @*Form Display Table END here*@
                
                </form>

Here is the JS script

@section Scripts {

                    <script type="text/javascript">
                        $("#Cities").hide();

                        $("#States").on("change", function () {

                            var cityDropdown = $('#Cities');
                            cityDropdown.empty();

                            $.getJSON('@Url.Action("GetCities")',
                            { id: $(this).val() },
                            function (cities) 
                            {
                                $.each(cities, function (i, city) 
                                {
                                    $("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                                });

                            });


                            $('#Cities').show();

                        });
                    </script>

                }

GetCities Action in Controller:

[HttpGet]
        public ActionResult GetCities(string id)
        {
            var cities = db.AustraliaCities.Where(c => c.AustraliaStateId == id).ToList();

            return Json(cities, JsonRequestBehavior.AllowGet);
        }

Can someone please help me?

Here is my site: http://overseasindians.com.au/

@section Scripts {

                    <script type="text/javascript">
                        $("#Cities").hide();

                        $("#States").on("change", function () {

                            var $cityDropdown = $('#Cities');
                            $cityDropdown.empty();

                            $.getJSON('@Url.Action("GetCities")',
                            { id: $(this).val() },
                            function (cities) 
                            {
                                $cityDropdown.append('<option value="">Select One...</option>').val("");
                                $.each(cities, function (i, city) 
                                {
                                    $cityDropdown.append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                                });

                            });


                            $cityDropdown.show();

                        });
                    </script>

                }

Hope this helps. it’s not tested, but you should catch the idea.