Category Archives: DropDownList

DropDownList

[RESOLVED]Need help to create Cascading DropDownList using MVC4 – C# from Database

I have 2 dropdown lists  (State and City) in my form and I want to show them as Cascading DropDownList.

When I select a State then I want to display only the related cities in that state.

My mode:

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

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



    public class Accommodation
    {
        [Key]
        public string A_Unique_Id { get; set; }

        [Display(Name = "Street")]
        public string Street { get; set; }

        [Required]
        [Display(Name = "Suburb")]
        public string Suburb { get; set; }

        [Display(Name = "City")]
        public string City { get; set; }

        [Display(Name = "State")]
        public string State { get; set; }

        public string SelectedAustraliaStateId { get; set; }
        public IEnumerable<SelectListItem> AustraliaStates { get; set; }


        public string SelectedAustraliaCityId { get; set; }
        public IEnumerable<SelectListItem> AustraliaCities { get; set; }
    }

Create.cshtml Get controller:

// GET: /Accommodation/Create
        [Authorize]
        public ActionResult Create()
        {

            var model = new Accommodation
            {
                AustraliaStates = db.AustraliaStates
                             .ToList() // this will fire a query, basically SELECT * FROM Products
                             .Select(x => new SelectListItem
                             {
                                 Text = x.AustraliaStateName,
                                 Value = x.AustraliaStateId
                             }),

                AustraliaCities = db.AustraliaCities
                             .ToList() // this will fire a query, basically SELECT * FROM Products
                             .Select(x => new SelectListItem
                             {
                                 Text = x.AustraliaCityName,
                                 Value = x.AustraliaCityId
                             });
                


            return View(model);
        }

Create.cshtml View

<td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    @Html.DropDownListFor(model => model.SelectedAustraliaStateId, Model.AustraliaStates, new {@class="DropDownFieldStyle" })

                                </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, new {@class="DropDownFieldStyle" })
                                </div>
                            </td>    
                        </tr>

I need to solution to show the DDL as Cascading DropDownList.

can someone please help me?

Thanks in advance.

Here is the form I am working on:

http://overseasindians.com.au/Accommodation/Create

Typical cascading dropdown lists only load the first list initially.  So in your case, you would load your States to the view.  Upon selecting a state, a JSON get-request is made back to your controller, where you’ll return a list of cities based on the
selected state.  Your Cities dropdown will also be hidden at the start, but will be revealed once a country is selected.  Also, you don’t want to return a model based on your two lists because a Create view needs to reserve a model specifically for the form
elements of the View.

public ActionResult Create()
{
  var states = db.Australiastates.ToList();

  ViewBag.stateList = states;

  return View();
}

In the above action, we create a list of States and pass them to the view as a ViewBag object.  We do NOT return any model to the view.

Now we create the View:

@model AppName.Models.YourFormModel

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

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

// make the get-request
$.getJSON('@Url.Action("GetCities")', { id: $(this).val() }, function (cities) {

// populate the Cities dropdown with returned data
$.each(cities, function (i, city) {
$("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
});

});

// show the Cities dropdown
$("#Cities").show();

}); </script> } <div> @Html.DropDownList("States", new SelectList(ViewBag.stateList, "AustraliaStateId", "AustraliaStateName"), "Select a state") </div> <div> <select id="Cities" /> </div>

In the above view, we have a dropdown list for both States and Cities, however you’ll notice that the Cities dropdown list is just a generic <select> element.  This is because we didn’t initially pass any data from the Create action to the view, so there’s
no reason to have the DropDownList helper.  We also have a "scripts-section" at the top, with a <script> block and some code inside.  The code is jQuery.  the first line hides our Cities dropdown because it will initially be empty, so it doesn’t need to be
shown immediately.  The 2nd part of the script is an on-change event for the States dropdown list.  On-change, we make a call to an action named "GetCities" where we pass an "id" param of the states dropdown value.  The action will use this param to find all
cities associated with the ID and return it back to the View.  Once the data is returned, we populate the Cities dropdown list, and then show the dropdown list so it can be visible.

Next, we need to add the "GetCities" action to take the State ID and return a list of Cities:

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

  return Json(cities, JsonRequestBehavior.AllowGet);
}

This action should be fairly obvious.  We used the state’s ID to gather a list of cities.  The only issue I had with this is that I didn’t see a "StateID" property in your AustraliaCities model, though I feel there should be one to create an association
between City and State.  I’ll let you determine how to use the state’s ID in the action to populate your Cities list.  In any case, once you have your list of cities, you return it as a JSON result.

That’s all there is to it.  This is a complete working solution.  Please let me know if you have questions.

Hi athelli_,

Thanks for your post.

athelli_reddy

Need help to create Cascading DropDownList using MVC4 – C# from Database

You can use JQuery, Please refer to this link:

#Creating cascading dropdownlists using MVC 4 And JQuery

http://jnye.co/Posts/12/creating-cascading-dropdownlists-using-mvc-4-and-jquery

Hope this can be helpful.

Best Regards,

Eileen

Thank you very much John for detailed explanation & your solution is working.

Can you please let me know how can I make State Dropdown menu field as a Mandatory field and show a client side validation if when the dropdown contains "Select a state" value.

public class AustraliaStates
    {
        [Key]
        public string AustraliaStateId { get; set; }
        
        [Required]  ->what else I can add here to make it as a Mandatory if there is "Select a state" value
        public string AustraliaStateName { get; set; }
    }

or do I need to write any java script??

[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.

[RESOLVED]How to make my 3 drpdownlist as a required fields

Hi, i added in my register view 3 dropdownlist to selecte the date of birth ( DAY  , MONTH, YEAR)

 @Html.DropDownList("DateOfBirthDay", Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Day --")
                @Html.DropDownList("DateOfBirthMonth", Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i) }), "-- Select Month --")
                @Html.DropDownList("DateOfBirthYear", Enumerable.Range(1900, 109).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Year --")
                

and i add them in my controller

// POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(string DateOfBirthDay , string DatehOfBirthMonth, string DateOfBirthYear, RegisterViewModel model)

but i would love to make them as a required files and if they are not, to return the form..

how to do?

Easiest way to validate a dropdown list is to check if the element contains a non-null value:

change button-type from submit to button

@using (Html.BeginForm())
{
  ... form elements here ...

  <input id="submitBtn" type="button" value="Submit" />
}

Then handle the on-click event to check if valid, then submit if validation passes

<script>
  $("#submitBtn").on("click", function () {
    var canSubmit = true;
    if ($("#DateOfBirthDay").val() == "") {
      canSubmit = false;
      alert = "Please select a day";
    }

    if ($("#DateOfBirthMonth").val() == "") {
      canSubmit = false;
      alert("Please select a month";
    }

    if ($("#DateOfBirthYear").val() == "") {
      canSubmit = false;
      alert("Please select a year";
    }

    if (canSubmit) {
      $("form").submit();
    }
  });
</script>

Alternatively, if these are model properties (DateOfBirthDay, DateOfBirthMonth, DateOfBirthYear), then you could give each a "[Required]" annotation in the model, and use a DropDownFor helper with a ValidationMessageFor helper message:

@Html.DropDownListFor(model => model.DateOfBirthDay, ...)
@Html.ValidationMessageFor(model => model.DateOfBirthDay)

using this method, it basically takes care of itself.

Not directly related to your question, but have you considered using a DatePicker. It provides better user experience and also solves your issues. You can use a JQuery UI DatePicker or some other DatePicker

Demo of JQueryUI DatePicker http://jqueryui.com/datepicker/

Integrating this in MVC

ASP.NET MVC 3: Integrating with the jQuery UI date picker and adding a jQuery
validate date range validator

[RESOLVED]How comes i cant get my 3 dropdownlist value?

Hi, i am trying to put 3 dropdownlist DAY , MONTH, YEAR in  stead of a single field : DateOfBirth

I modify my register view page  Account/Register.cshtml  like this :

        <div class="form-group">
            @Html.LabelFor(m => m.DateOfBirth, new { @class = "col-md-4 control-label" })
            <div class="col-md-8">
                @Html.DropDownList("DateOfBirthDay", Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Day --")
                @Html.DropDownList("DateOfBirthMonth", Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i) }), "-- Select Month --")
                @Html.DropDownList("DateOfBirthYear", Enumerable.Range(1900, 109).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Year --")
                @Html.ValidationMessageFor(m => m.DateOfBirth)
            </div>
        </div>

I updated my controller with the following :

 //
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register([Bind(Include = "DateOfBirthDay,DateOfBirthMonth,DateOfBirthYear")] RegisterViewModel model)

this is my  RegisterViewModel : (AccountViewModels.cs)

 public class RegisterViewModel
    {
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [DataType(DataType.EmailAddress)]
        [RegularExpression(@"^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$", ErrorMessageResourceName = "Invalid", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "UserName", ResourceType = typeof(ViewRes.Names))]
        public string UserName { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [StringLength(100, ErrorMessageResourceName = "PasswordMinLength", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings), MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password", ResourceType = typeof(ViewRes.Names))]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "ConfirmPassword", ResourceType = typeof(ViewRes.Names))]
        [Compare("Password", ErrorMessageResourceName = "PasswordMustMatch", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        public string ConfirmPassword { get; set; }

        // New Fields added to extend Application User class:
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "FirstName", ResourceType = typeof(ViewRes.Names))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "LastName", ResourceType = typeof(ViewRes.Names))]
        public string LastName { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "Sex", ResourceType = typeof(ViewRes.Names))]
        public string Sex { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "DateofBirth", ResourceType = typeof(ViewRes.Names))]
        [DataType(DataType.DateTime)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DateOfBirth { get; set; }

        public DateTime DateOfRegistration { get; set; }

        public bool UserNewsletter { get; set; }

        public string DefaultLanguage { get; set; }

        public string RealUserLanguage { get; set; }
        
        // Return a pre-poulated instance of AppliationUser:
        public ApplicationUser GetUser()
        {
            //Generate random code
            string randomcode = "";
            Random random = new Random();
            int length = 8;
            for (int i = 0; i < length; i++)
            {
                if (random.Next(0, 3) == 0)                     //if random.Next() == 0 then we generate a random character
                {
                    randomcode += ((char)random.Next(65, 91)).ToString();
                }
                else                                            //if random.Next() == 0 then we generate a random digit
                {
                    randomcode += random.Next(0, 9);
                }
            }



            //Get the language of the user
            string defaultlanguage = "en";
            string langName = "en";
            if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0)
            {

                defaultlanguage = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2);

                if (defaultlanguage == "it")
                {
                    langName = "it";
                }
                if (defaultlanguage == "fr")
                {
                    langName = "fr";
                }
                if (defaultlanguage == "es")
                {
                    langName = "es";
                }

            }



            var user = new ApplicationUser()
            {

                UserName = this.UserName,

                FirstName = this.FirstName,

                LastName = this.LastName,

                Sex = this.Sex,

                DateOfBirth = this.DateOfBirth,

                DateOfRegistration = DateTime.Now,

                PasswordNotHashed = this.ConfirmPassword,

                CodeVerification = randomcode,

                UserActive = true,

                UserNewsletter = this.UserNewsletter,

                DefaultLanguage = langName,

                RealUserLanguage = defaultlanguage,

            };
            return user;
        }
    }

But when i try to get the 3 dropdownlist data in my controller it looks like they don’t exist… why?

example

 DateOfBirthYear = model.DateOfBirthYear;

Thanks

Hi,

Either you can go for Strongly Typed DropdownListFor or if you want to stick for the same code then you can pass the parameters in your post method like below -

YourPostMethod(string DateOfBirthDay , string DatehOfBirthMonth, string DateOfBirthYear)

{



}

Hi, like this i can see them, but how can i make them as a required fields?

because, when i register,  if i don’t choose any day or month or year i get error :

Erreur du serveur dans l'application '/'.

La chaîne n'a pas été reconnue en tant que DateTime valide.

Description : Une exception non gérée s'est produite au moment de l'exécution de la requête Web actuelle. Contrôlez la trace de la pile pour plus d'informations sur l'erreur et son origine dans le code. 

Détails de l'exception: System.FormatException: La chaîne n'a pas été reconnue en tant que DateTime valide.

Erreur source: 


Ligne 820 :                {
Ligne 821 :                    // do for invalid date
Ligne 822 :                    DateTime FullDateOfBirthLastFormatDate = Convert.ToDateTime(FullDateOfBirthLast);
Ligne 823 :                    user.DateOfBirth = FullDateOfBirthLastFormatDate;
Ligne 824 :

you should add the three down drown fields to the view model and make them required.

Setup DropDownListFor in Create view to use for states and form won't submit

Setup DropDownListFor in Create view to use for states and form won’t submit.

Here is the controller code:

‘<<<(STATE DROP-DOWN)>>>
Dim ListStates As List(Of KeyValuePair(Of String, String)) = FormItems.GetStates()
Dim States As New List(Of SelectListItem)()

For Each item As KeyValuePair(Of String, String) In ListStates
States.Add(New SelectListItem() With {.Text = item.Key, .Value = item.Value})
Next
ViewBag.State = States

‘>>>>>>>>>>>>>>>>>>

The controller code works fine and builds the dropdown list in the create view; here is the line in the create view:

@Html.DropDownListFor(Function(model) model.State, ViewBag.State)

I pick a state and fill out the other parts of the form and click create but it won’t submit and highlights the state dropdown.

What could be the problem?

Hi belcherman,

Do you mean the data of DropDownList is not submit?

If that is the case, how do you receive that data? The action code may like this below:

public ActionResult Index([your model] m)
{

}
public ActionResult Index(string state)
{

}

Please use the developer to check the posted data whether the necessary data have been submitted.

Best Regards

Starain Chen

[RESOLVED]Post Backs Using View Models

This problem has been driving me crazy for past few weeks I wonder if anyone has some advice for me.

I have a view model, that contains 5 drop down lists.  When I create the initial view and send it out,  all 5 select lists have values from the viewmodel.  The user can see and select any value in any of them.  However, when I post back only 1 of the select
lists contain any values!

The problem this presents of course, is this, in the post back ActionMethod I first check ModelState.IsValid if it’s not valid I simply return the posted Viewmodel, but guess what those selectlists that had no values on the post now show nothing along with
the errors telling them to select something.

Ever seen this symptom before?

The issue is likely to be around the names the select elements are getting, as to be considered a list of values they need the right indexes in their names, andor your parameter for the POST action.  Post the relevant sections of the view where the lists
are created and the actions too.

One other bit of information…

I have an extension method returning this type  

public static List<SelectListItem>

The view model stages the content like this:

 public List<SelectListItem> EndHourSelectList { get; set; }

In the Validation implementation on the post back  (Locals) I see this:

+EndHourSelectList Count = 0×00000000 System.Collections.Generic.List<System.Web.Mvc.SelectListItem>

Notice the count is zero!  This implies that MVC some how created a new instance doesn’t it?  But if so why did the other one have values?

 

//This one returns values   
@Html.DropDownListFor(p => p.TT.area_worked_in, Model.AreaSelectList)

//these like this do not
@Html.DropDownListFor(p => p.StartHourSelectList, Model.StartHourSelectList);

p is the ViewModel  and TT is a type within the ViewModel

Here’s a Viewmodel example for one of the four that do not post back values in the selectlist

public List<SelectListItem> StartHourSelectList { get; set; }

Finally I build the list like this:

        public static List<SelectListItem> SetTimeTrackMinutes(this List<SelectListItem> SelectList)
        {
            if (SelectList == null) throw new InvalidOperationException("STTM300-Must Initialize the list before calling this method");
            SelectList.Add(new SelectListItem { Selected = true, Text = "Select Minutes (15 min incr.)", Value = SelectListValues.NotSelected.ToString() });
            SelectList.Add(new SelectListItem { Selected = false, Value = "0", Text = "00 (Minutes)" });
            SelectList.Add(new SelectListItem { Selected = false, Value = "15", Text = "15 (Minutes)" });
            SelectList.Add(new SelectListItem { Selected = false, Value = "30", Text = "30 (Minutes)" });
            SelectList.Add(new SelectListItem { Selected = false, Value = "45", Text = "45 (Minutes)" });
            return SelectList;
        }

I think you’re telling me I need a POCO class to model the minutes in order for the minutes to have Names?

You need a property on the view model that holds the current item

public class ViewModel
{
    public string SelectedHour { get; set; }
    public List<SelectListItem> StartHourSelectList { get; set; }
}

Controller

public ActionResult Index()
{
    ViewModel model = new ViewModel();

    SetupModel(model);

    return View(model);
}

[HttpPost]
public ActionResult Index(ViewModel model)
{
    SetupModel(model);

    return View(model);
}

private void SetupModel(ViewModel model)
{
    model.StartHourSelectList = new List<SelectListItem>();
    model.StartHourSelectList.SetTimeTrackMinutes();
}

View

@using(Html.BeginForm())
{
    @Html.DropDownListFor(p => p.SelectedHour, Model.StartHourSelectList);
    <p>
        <input type="submit" value="submit"/>
    </p>
}

Thanks Aidy;

I’ll give it a try and post back results.

Aidy;

 One question, my current post looks like this:

  @using (@Html.BeginForm("TimeTrackingForm", "ControllerName", FormMethod.Post))

Representing the TimeTrackingFrom action method in the controller that takes a Viewmodel as input parm like this:

public ViewResult TimeTrackingForm(VMTimeTrackForm TTF)

The view is strongly typed to the VMTimeTrackFrom type, so shouldn’t this be all I need on the @Html.BeginForm?

Ok Aidy very good you helped me solve this infuriating problem… I think I have a better understanding of the secretive Razor binding engine now. 

Here’s the general set of rules I’ll be following from now on.

  1. Any view model that uses an IEnumberable<ofSomething> and a DropDownListFor (or other HTML.Helper method) must specify in the first parameter where to place the selected value like this ->  DropDownListFor(p=>StuffTheSelectedValue, TheSelectList), where
    p is the Viewmodel.  The variable "StuffTheSelectedValue" in my case was a string with public Getter, Setters. [I didn't have it at first]
  2. If you don’t get that first parm right, MVC will return NOTHING for the SelectItemList itself even if it wen’t out the first time ok.  It will not signal an error anywhere in the compile, or the post back, rather it will just show up with nothing.  This
    is most likely done by the binder part of Razor whereby prior to seeing the post back in the controller, it initializes a new instance of the object, parses the querystrings and plugs the values by name where they belong.  If it can’t find anything to plug
    it leaves it blank.
  3. If you have implemented IValidatableObject the view state will most likely be invalid if the first parm was wrong, provided you are checking for something relevant or the model has proper data annotations.
  4. If the controller checks the view state and simply returns the view when the state is invalid, it will NO LONGER have any items to select!  The user will see the error messages but will not be able to do anything for them.
  5. You do not have to re-initialize the view content, if and only if, you get the first parameter correct in the DropDownListFor correct. (Or any other HTML "helper" method)
  6. If you just return the invalid view from the POST back and
    everything is correct (meaning the binder found everything to fill in)
    ,  all of the content is still there.

I too, after debugging this for a long time, had created my own post back initializes, but will not do that any more as it is a sign that something else isn’t right.  At a minimum, to me anyway, there should be some type of warning at compile time that this
could happen.  

Symptoms of this problem are :

  1.  PostBacks loose data and require re-initialization of the ViewModel.
  2. Users see data annotation or other ValidationResult errors but have no way to fix them.
  3. You find when breaking into the PostBack (very first line in the Action Method) in the controller that the viewmodel is missing data.
  4. You are writing re-initialization routines just for Post Backs.

Solution:

  1. The query strings that are returned are name/value pairs, if there is no name of MVC on the server side it will not do anything which is correct behavior.
  2. If you are using strongly typed views your BeginForm only needs to specify the controller post back action method that takes that strong type as it’s first parm.
  3. This then is the MVC method for maintaining ViewState without using ViewState.

My final solution was this in the view:

  @Html.DropDownListFor(p => p.SelectedStartHour, Model.StartHourSelectList);

This in the View Model:

public List<SelectListItem> StartHourSelectList { get; set; }
public string SelectedStartHour { get; set; }

Notice the first parm on the DropDownListFor pointed to a string value in the ViewModel, simple and it relieved me of a lot of pain in trying to understand this MVC thing.

One last thing Aidy, 

I got rid of all my re-initialization logic in the Post back…  it’s wasn’t needed any longer.  And Thanks a bunch for your help.

[RESOLVED]How to save dropdown selected text into database using EF In MVC4?

Hi Friends ,

           I would like to know how to save  Dropdown selected text  and Checkbox checked value in data base using EF.Can anyone provide example Code ?

Thx in advance 

-Ernesto Karthik

 

HI  Dharmesh ,

                       I have  binded the dropdown values in the dropdown. i would like to save the selected Text in the dropdown in another table.How to do that using EF 

Thx ,

-Ernesto Karthik

 

 

Hi Karthik ,

I will suggest use Begin form in your view , so you can pass selected values to your controller/ action. Once you get this value in  Post action, you can call EF method or DAL method.

For example :

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
    {

/// Dropdown 1

/// Dropdown 2
<input type="submit" value="Html PsBk Click" /> }

Now in "ActionName" you need to write code to read this param.

[HttpPost]
        public ActionResult ActioName(PersonnelModel Pmodel)
        {
   // Read model data from this param ex. Pmodel.dropdown1 // Pmodel.dropdown2         
----
-- }

For more details : http://msdn.microsoft.com/en-us/library/dd505244(v=vs.118).aspx

1. Entity class must have properties to hold the text and value

2. In View, keep hidden with name of above text property

3. In View, keep dropdown for above value property

3. Update the hidden value wit dropdown selecteditem on selection of dropdown at client side

then the text also gets posted

EF creates POCO classes of your database.  MVC allows you to send those objects to the user to edit and post.  In your controller you can take an instance of that class like this:

public ActionResult SavedPerson(Person person){
int rowssaved = 0;
//first see if model state is valid
if (ModelState.IsValid){

using (var db = new myEFEntities()){
   db.Person.Add(person);
   rowsaved=db.SaveChanges();
}
var results = new VMSavedPerson(person, rowsaved);
return View(SavedPerson);
}

[RESOLVED]Something is triggering unobtrusive validation, but what?

I have a fairly simple mvc form with validation.  One of the sections is a dynamically added partial view (add a new row with a button click).  Something in there is triggering a validation error, but I can’t find it.  It is requiring the IdentificationType
dropdown have a selected value, but as far as I can see, there is no "Required" set anywhere in the code.  There are 4 different sections setup as dynamiclly added partials and they are all fine.  The only difference I can see is the id type is a dropdown,
and it is the only one triggering the validation error.  Is this a dropdown thing?  Here is some code:

Partial view:

        <div class="IdentPartial" > 
             <div class="formGroup-Short">
                <div class="editor-label">
                    @*@Html.HiddenFor(m => m.IdentificationCounter, new { @class="iHidden" })*@
                    @Html.Label("Identification Type")
                </div>
                <div class="editor-field">
                     @Html.DropDownListFor(m => m.IdentificationModel[Model.IdentificationCounter].IdentificationType, new SelectList(Model.IDTypes, "Value", "Text"), "Select", new { style = "width: 150px;" })
                </div>
            </div>
        
            <div class="formGroup-Short">
                <div class="editor-label">
                    @Html.Label("Identification Number")
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.IdentificationModel[Model.IdentificationCounter].IdentificationNumber, new { style = "width:120px" })
                </div>
            </div>

            <div class="formGroup">
                <div class="editor-label"  style="width: 100px">
                    @Html.Label("Issuing State")
                </div>
                <div class="editor-field">
                    @Html.DropDownListFor(m => m.IdentificationModel[Model.IdentificationCounter].IssuingState, new SelectList(Model.State, "Value", "Text", "OR"), "Select", new { style = "width: 65px; margin-right:20px;" })
                </div>
            </div>
        </div>

ID Model:

    public class IdentificationMetadata
    {

        [DisplayName("Identification Type")]
        public string IdentificationType { get; set; }

        [DisplayName("Identification Number")]
        public string IdentificationNumber { get; set; }
        
        [DisplayName("State")]
        public string IssuingState { get; set; }
    }

jQuery script, button event:

            $("#AddId").on("click", function () {
                var itemIndex = $(".IdentPartial .iHidden").length;
                $.get(
                    "@Url.Action("NewIdentRow")/" + itemIndex,
                    function (data) {
                        $("#IdentDataSection").append(data);
                    });
            });

Can you send the exact error message you are getting it?

As far as i see you don’t have a required field in your model.

I finally found the solution, the IdentificationType was a not null int in the DB.  I made it nullable in the DB and changed it int he model, now if doesnt trigger the validation.

[RESOLVED]multiple search option with cascading dropdown and MVC.Paging

how can i use multiple search options to get number of paged records

multiple search option like country ,state ,city ,gender, and etc…

here i created a controller browseallmemmbers where search criteria is working 

private const int defaultPageSize = 10;
       
        private IList<Profile> getAllmembers = new List<Profile>();
        public ActionResult BrouseAllMem(int? page, long? stateid, long? countryid,long? cityid)
        {

            int currentPageIndex = page.HasValue ? page.Value : 1;

            ViewData["countryid"] = countryid;
            ViewData["Stateid"] = stateid ;
            ViewData["cityid"] = cityid ;
           
            IList<Profile> members = this.getAllmembers;

           
            IQueryable<Profile> mm = db.Profiles.OrderByDescending(c => c.pid);
            if (countryid > 0)
            {
                
                mm = mm.Where(p => p.countryid == countryid);
            }
            if (stateid > 0)
            {
                mm = mm.Where(p => p.stateid == stateid);
            }
            if (cityid > 0)
            {
                mm = mm.Where(p => p.cityid  == cityid);
            }

           
            members = mm.OrderByDescending(p => p.pid).ToPagedList(currentPageIndex, defaultPageSize);
 
            ViewBag.cityid = new SelectList(db.citytables, "cityid", "cityname", ViewData["cityid"]);
            ViewBag.countryid = new SelectList(db.Countries, "COUNTRYID", "countryname", ViewData["countryid"]);
            ViewBag.stateid = new SelectList(db.states, "stateid", "statename", ViewData["stateid"]);
                      
            return View(members);
        }

View where result is displaying

@*@model IEnumerable<LovNMarProj.Models.Profile>*@
@using MvcPaging
@model IPagedList<LovNMarProj.Models.Profile>
@{
    ViewBag.Title = "BrouseAllMem";
    Layout = "~/Views/Shared/_LayoutTEM.cshtml";
}
@using (Html.BeginForm("BrouseAllMem", "Home", FormMethod.Get))
{
<div class="page-header">
    <div class="panel panel-default">
        <div class="panel-heading">All Members</div>
        <div class="panel-body">
            <div class="col-sm-3 col-md-3 pull-left">
                <div class="input-group input-group-sm">
                    @*<input class="form-control" id="appendedInputButton" type="text" name="member_name" placeholder="Name" value="@ViewData["member_name"]" />*@
                   
                </div>
            </div>
            @Html.DropDownList("countryid", ViewBag.countryid as SelectList, "Select a Country", @ViewData["countryid"])

            @Html.DropDownList("stateid",null ,string.Empty , @ViewData["stateid"])

            @Html.DropDownList("cityid",null ,string.Empty , @ViewData["cityid"])

            <div class="col-sm-3 col-md-3 pull-right" >
                <button class="btn" type="submit">
                    <i class="glyphicon glyphicon-search"></i>
                </button>
            </div>
        </div>
        <ul class="list-group">
            
            @foreach (var item in Model)
            {
                var gender = "Female"; if (@item.gender == "M") { gender = "Male"; } 
                var pimage = "no_avatar.gif"; 
                if (@item.photo != null && @item.photo  != "") { pimage = @item.photo ; }
                
                
                
                <li class="list-group-item ">
                    <div class="row">
                        <div class="col-sm-9">
                            <p> <strong>@item.headline</strong></p>
                        </div>
                        <div class="col-lg-3 text-muted text-right small">
                            Joined On: @item.profiledate
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-1">

                            <img src="~/profilepic/@pimage" class="img-thumbnail" />
                        </div>
                        <div class="col-sm-3">
                            <h5>
                                @item.fname
                                &nbsp;
                                @item.lname<small>(@gender)</small>
                            </h5>
                            <p>
                                @item.Country.countryname  -
                                @item.state.statename -
                                @item.citytable.cityname 
                            </p>
                        </div>
                        <div class="col-sm-5">
                            About:<p> @item.whoami</p>
                        </div>
                        <div class="col-sm-3">
                           Looking For:<p> @item.lookingfor</p>
                        </div>
                    </div>








                </li>
            }

        </ul>
        <div class="panel-footer">
            <div class="pager">
                @Html.Raw(Html.Pager(
            new Options
            {
                PageSize = Model.PageSize,
                TotalItemCount = Model.TotalItemCount,
                CurrentPage = Model.PageNumber,
                ItemTexts = new ItemTexts() { Next = "Next", Previous = "Previous" },
                ItemIcon = new ItemIcon() { First = "icon-backward", Previous = "icon-chevron-left", Next = "icon-chevron-right", Last = "icon-forward" },
                TooltipTitles = new TooltipTitles() { Next = "Next page {0}", Previous = "Previous page {0}", Page = "Go to page {0}" },
                Size = Size.normal,
                Alignment = Alignment.centered,
                IsShowControls = true,
                IsShowFirstLast = true,
                IsShowPages = true
            }, new { countryid = ViewData["countryid"], stateid = ViewData["stateid"], cityid = ViewData["cityid"] }))
            </div>

        </div>
    </div>
</div>
}
<script type="text/jscript">
    $(function () {

        $('#countryid').ready(function () {


            //$('#stateid').empty();
            //$('#cityid').empty();

            $.getJSON('/Kas/StateList/' + $('#countryid').val(), function (data) {
                var items = "";
                $.each(data, function (i, stateid) {
                    items += "<option value='" + stateid.Value + "'>" + stateid.Text + "</option>";
                });

                $('#stateid').html(items);
                $('#stateid').trigger("change");

            });
        });



        $('#countryid').change(function () {

            $.getJSON('/Kas/StateList/' + $('#countryid').val(), function (data) {
                var items = '';
                $.each(data, function (i, stateid) {
                    items += "<option value='" + stateid.Value + "'>" + stateid.Text + "</option>";
                });
                $('#stateid').html(items);

            });
        });

        $('#stateid').change(function () {
            $.getJSON('/Kas/Citylist/' + $('#stateid').val(), function (data) {
                var items = '';
                $.each(data, function (i, cityid) {
                    items += "<option value='" + cityid.Value + "'>" + cityid.Text + "</option>";
                });
                $('#cityid').html(items);



            });
        });





    });

</script>

it shows the result properly but if i go to next page search criteria is gone

how to keep search result and paging both

 with one search option its works but with multiple search its not working

Hi pjpatil,

Base on your code, I found that you are using ViewData and ViewBag with same key, which are conflict, in other words, the
ViewData data will be override.

Please use the different key to store current search conditions.

To keep the conditions, you just need to store them as parameters in the URL (Html.PagedListPager), and in the action has the corresponding parameters to get that data.

Best Regards

Starain Chen

[RESOLVED]how to chek if 3 data taken form a form are a valid Date

Hi, i got 3 dropdownlist with DAY, MONTH and YEAR

 @Html.DropDownList("DateOfBirthDay", Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Day --")
                @Html.DropDownList("DateOfBirthMonth", Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i) }), "-- Select Month --")
                @Html.DropDownList("DateOfBirthYear", Enumerable.Range(1900, 109).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Year --")
                

Each one have a numerical value,  what i would love to do is to check if putting them together i got a real date

example

var mynewdate = DateOfBirthDay + "/" + DateOfBirthMonth "/" + DateOfBirthYear

how to chek if this will be a real date? (example, if i put 31/02/2014 it is not a real date)

and after this, how to convert this var to be a date?

Thanks

Hi, u done this code, in my controller

// POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(string DateOfBirthDay , string DatehOfBirthMonth, string DateOfBirthYear, RegisterViewModel model)

                DateTime fromDateValue;
                string FullDateOfBirth = DateOfBirthYear + "-" + DatehOfBirthMonth + "-" + DateOfBirthDay;
                string FullDateOfBirthLast = DateOfBirthYear + "-" + DatehOfBirthMonth + "-28";
                var formats = new[] { "yyyy-MM-dd" };
                if (DateTime.TryParseExact(FullDateOfBirth, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
                {
                    // do for valid date
                    DateTime FullDateOfBirthFormatDate = Convert.ToDateTime(FullDateOfBirth);
                    user.DateOfBirth = FullDateOfBirthFormatDate;
                }
                else
                {
                    // do for invalid date
                    DateTime FullDateOfBirthLastFormatDate = Convert.ToDateTime(FullDateOfBirthLast);
                    user.DateOfBirth = FullDateOfBirthLastFormatDate;

                }

but i get error

La chaîne n'a pas été reconnue en tant que DateTime valide.

Description : Une exception non gérée s'est produite au moment de l'exécution de la requête Web actuelle. Contrôlez la trace de la pile pour plus d'informations sur l'erreur et son origine dans le code. 

Détails de l'exception: System.FormatException: La chaîne n'a pas été reconnue en tant que DateTime valide.

Erreur source: 


Ligne 820 :                {
Ligne 821 :                    // do for invalid date
Ligne 822 :                    DateTime FullDateOfBirthLastFormatDate = Convert.ToDateTime(FullDateOfBirthLast);
Ligne 823 :                    user.DateOfBirth = FullDateOfBirthLastFormatDate;
Ligne 824 :

Fichier source : c:FRANCESCOProjectHairCollection3HairCollection3ControllersAccountController.cs    Ligne : 822 

Trace de la pile: 

why? what is worng?

Hi,

If possible make your datetime property nullable -> datetime ? to accept the null value and do the null check in your controller.

Hi grafic,

Please modify your code like this:

DateTime fromDateValue;
                string FullDateOfBirth = DateOfBirthYear + "-" + DatehOfBirthMonth + "-" + DateOfBirthDay;
                string FullDateOfBirthLast = DateOfBirthYear + "-" + DatehOfBirthMonth + "-28";
                var formats = new[] { "yyyy-MM-dd" };
                if (DateTime.TryParseExact(FullDateOfBirth, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
                {
                    user.DateOfBirth = fromDateValue;
                }

Best Regards

Starain Chen

Hi
Starain chen…
,

i did two variables : FullDateOfBirth
and  FullDateOfBirthLast
because i wanna check if FullDateOfBirth 
is a date and in that case i would love to save it in my filed
DateOfBirth
, but if is not a date i thoght that i could do a default date which contains the year, the month, and after the day 28, because it always exist a month with 28 days…

so in case that my var FullDateOfBirth
it is not a date, i would love to save the other one FullDateOfBirthLast 
in my field DateOfBirth..

How to do?

Hi grafic,

Base on the error message, it means that that value can’t convert to datetime. So you need check the value of
FullDateOfBirthLast.

Best Regards

Starain Chen

Hi
Starain chen…
, i updated with your code but it skips and it looks like the date is not a valid date, in fact ias a date of birth i found the date of today…

This is the code i done :

//Set the date of birth
                DateTime fromDateValue;
                string FullDateOfBirth = user.DateOfBirthYear + "-" + user.DateOfBirthMonth + "-" + user.DateOfBirthDay;
                string FullDateOfBirthLast = user.DateOfBirthYear + "-" + user.DateOfBirthMonth + "-28";
                var formats = new[] { "yyyy-MM-dd" };
                if (DateTime.TryParseExact(FullDateOfBirth, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
                {
                    user.DateOfBirth = fromDateValue;
                }
                else
                {
                    DateTime fromDateValueLast;
                    if (DateTime.TryParseExact(FullDateOfBirthLast, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValueLast))
                    {
                        user.DateOfBirth = fromDateValueLast;
                    }
                    else
                    {
                        user.DateOfBirth = DateTime.Now;
                    }
                }

i done the debug and the for the code the 2 dates ( FullDateOfBirth , FullDateOfBirthLast ) are not a valid dates …

when i done the debug i got this values :

FullDateOfBirth = "1914-9-6"

fromDateValue (Date = {0001-01-01 00:00:00})

FullDateOfBirthLast  = "1914-9-28"

fromDateValueLast (Date = {0001-01-01 00:00:00})

What is wrong?

Hi grafic,

Please use this format:

var formats = new[] { "yyyy-MM-dd", "yyyy-M-dd", "yyyy-M-d","yyyy-MM-d" };

Best Regards

Starain