Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

MVC: Trying to access dropdown values from Home Controller

Options
  • 07-10-2019 12:33pm
    #1
    Registered Users Posts: 29


    Hi folks,

    I'm currently working on this solution, a 3 layer cascading dropdown list, (I've copied the solution into my Visual Studio 2019 and running it from there). I've added in an additional function that saves the value in each dropdown, to my SQL DB, (see below).

    As I'm a new user I cannot post a fiddle for this but if you go on dotnetfiddle and paste in "SDXNlb" you can see the solution I'm referring to...

    public ActionResult SaveResults(SaveResults SaveResultsDB)

    {

    SaveResultsViewModelDBContext iDB = new SaveResultsViewModelDBContext();

    SaveResultsDB.Make = _MyCity.ToString();
    SaveResultsDB.Model = _MyLocality.ToString();


    iDB.SaveResultsDBs.Add(SaveResultsDB);
    iDB.SaveChanges();
    iDB.Dispose();


    //InterchangeDB.Model = "2A";
    //InterchangeDB.Specification = "3A";
    //iDB.InterchangeDBs.Add(InterchangeDB);
    //iDB.SaveChanges();
    //iDB.Dispose();
    //return View();
    return RedirectToAction("Index");

    }


    When I hard code in the values as I have done in the //commented code above, the results do save to my DB so the code is being triggered, I just cannot get it to work when I try to save the actual dropdown values, I keep getting back NULL values.

    Any help much much appreciated!


Comments

  • Registered Users Posts: 29 MilitaryRoad


    Just posting the code I'm trying to use:

    MODEL:

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

    namespace Ashish
    {
    public class City
    {
    public int ID { get; set; }
    public string Name { get; set; }
    }
    public class Locality
    {
    public int ID { get; set; }
    public int CityID { get; set; }
    public string Name { get; set; }
    }
    public class SubLocality
    {
    public int ID { get; set; }
    public int LocalityID { get; set; }
    public string Name { get; set; }
    }
    public class Coordinates
    {
    public int CityID { get; set; }
    public float Latitude { get; set; }
    public float Longitude { get; set; }
    }

    public class Repository
    {
    public static List<City> FetchCities()
    {
    List<City> cities = new List<City>();
    cities.Add(new City() { ID = 1, Name = "Faridabaad" });
    cities.Add(new City() { ID = 2, Name = "Greater Noida" });
    return cities;
    }
    public static List<Locality> FetchLocalities()
    {
    List<Locality> localities = new List<Locality>();
    localities.Add(new Locality() { ID = 1, CityID = 1, Name = "East Faridabaad" });
    localities.Add(new Locality() { ID = 2, CityID = 1, Name = "West Faridabaad" });
    localities.Add(new Locality() { ID = 3, CityID = 2, Name = "East Noida" });
    localities.Add(new Locality() { ID = 4, CityID = 2, Name = "West Noida" });
    return localities;
    }
    public static List<SubLocality> FetchSubLocalities()
    {
    List<SubLocality> subLocalities = new List<SubLocality>();
    subLocalities.Add(new SubLocality() { ID = 1, LocalityID = 1, Name = "East Faridabaad Region 1" });
    subLocalities.Add(new SubLocality() { ID = 2, LocalityID = 1, Name = "East Faridabaad Region 2" });
    subLocalities.Add(new SubLocality() { ID = 3, LocalityID = 2, Name = "West Faridabaad Region 1" });
    subLocalities.Add(new SubLocality() { ID = 4, LocalityID = 2, Name = "West Faridabaad Region 2" });
    subLocalities.Add(new SubLocality() { ID = 5, LocalityID = 3, Name = "East Noida Region 1" });
    subLocalities.Add(new SubLocality() { ID = 6, LocalityID = 3, Name = "East Noida Region 2" });
    subLocalities.Add(new SubLocality() { ID = 7, LocalityID = 4, Name = "West Noida Region 1" });
    subLocalities.Add(new SubLocality() { ID = 8, LocalityID = 4, Name = "West Noida Region 2" });
    return subLocalities;
    }
    public static List<Coordinates> FetchCoordinates()
    {
    List<Coordinates> coordinates = new List<Coordinates>()
    {
    new Coordinates() { CityID = 1, Latitude = 100.00F, Longitude = 100.00F },
    new Coordinates() { CityID = 2, Latitude = 200.00F, Longitude = 200.00F }
    };
    return coordinates;
    }
    }

    public class ViewModel
    {

    [Required(ErrorMessage = "Please enter a project name")]
    [Display(Name = "Project")]
    public string ProjectName { get; set; }
    [Required(ErrorMessage = "Please enter a developer name")]
    [Display(Name = "Developer")]
    public string DeveloperName { get; set; }

    [Required(ErrorMessage = "Please select a city")]
    [Display(Name = "City")]
    public int? SelectedCity { get; set; }
    [Required(ErrorMessage = "Please select a locality")]
    [Display(Name = "Locality")]
    public int? SelectedLocality { get; set; }
    [Required(ErrorMessage = "Please select a sub locality")]
    [Display(Name = "Sub Locality")]
    public int? SelectedSubLocality { get; set; }
    public SelectList CityList { get; set; }
    public SelectList LocalityList { get; set; }
    public SelectList SubLocalityList { get; set; }
    }



    }



    /////////////////////////////////////////////////////////////////////////////////

    VIEW:

    @model Ashish.ViewModel
    @{
    Layout = null;
    }

    <!DOCTYPE html>>

    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style type="text/css">
    div {
    margin: 10px;
    }
    label {
    display: inline-block;
    width: 100px;
    }
    input[type="text"] {
    box-sizing: border-box;
    width: 200px;
    }
    select {
    width: 200px;
    }
    input[type="submit"] {
    margin-left: 115px;
    }

    .field-validation-error {
    display:block;
    margin-left: 110px;
    color: #ff0000;
    }

    </style>
    </head>

    <body>


    @using (Html.BeginForm())
    {
    <div>
    @Html.LabelFor(m => m.ProjectName)
    @Html.TextBoxFor(m => m.ProjectName)
    @Html.ValidationMessageFor(m => m.ProjectName)
    </div>
    <div>
    @Html.LabelFor(m => m.DeveloperName)
    @Html.TextBoxFor(m => m.DeveloperName)
    @Html.ValidationMessageFor(m => m.DeveloperName)
    </div>
    <div>
    @Html.LabelFor(m => m.SelectedCity)
    @Html.DropDownListFor(m => m.SelectedCity, Model.CityList, "Please select")
    @Html.ValidationMessageFor(m => m.SelectedCity)
    </div>
    <div>
    @Html.LabelFor(m => m.SelectedLocality)
    @Html.DropDownListFor(m => m.SelectedLocality, Model.LocalityList, "")
    @Html.ValidationMessageFor(m => m.SelectedLocality)
    </div>
    <div>
    @Html.LabelFor(m => m.SelectedSubLocality)
    @Html.DropDownListFor(m => m.SelectedSubLocality, Model.SubLocalityList, "")
    @Html.ValidationMessageFor(m => m.SelectedSubLocality)
    </div>


    <input type="submit" value="save" />
    }


    <!-- JS includes -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

    <script type="text/javascript">
    var localityUrl = '@Url.Action("FetchLocalities")';
    var subLocalityUrl = '@Url.Action("FetchSubLocalities")';
    var coodinatesUrl = '@Url.Action("FetchCoordinates")';
    var localities = $('#SelectedLocality');
    var subLocalities = $('#SelectedSubLocality');
    $('#SelectedCity').change(function() {
    localities.empty();
    subLocalities.empty();
    $.getJSON(localityUrl, { ID: $(this).val() },function(data) {
    if (!data) {
    return;
    }
    localities.append($('<option></option>').val('').text('Please select'));
    $.each(data, function(index, item) {
    localities.append($('<option></option>').val(item.Value).text(item.Text));
    });
    });
    $.getJSON(coodinatesUrl, { ID: $(this).val() }, function(data) {
    console.log(data);
    });
    })
    $('#SelectedLocality').change(function() {
    subLocalities.empty();
    $.getJSON(subLocalityUrl, { ID: $(this).val() },function(data) {
    if (!data) {
    return;
    }
    subLocalities.append($('<option></option>').val('').text('Please select'));
    $.each(data, function(index, item) {
    subLocalities.append($('<option></option>').val(item.Value).text(item.Text));
    });
    });
    })

    </script>
    </body>
    </html>


    //////////////////////////////////////////////////////////////////////////////////

    CONTROLLER:

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

    namespace Ashish
    {
    public class HomeController : Controller
    {
    [HttpGet]
    public ActionResult Index()
    {
    ViewModel model = new ViewModel();
    //model.SelectedCity = 2;
    //model.SelectedLocality = 3;
    //model.SelectedSubLocality = 6;
    ConfigureViewModel(model);
    return View(model);
    }

    [HttpPost]
    public ActionResult Index(ViewModel model)
    {
    if (!ModelState.IsValid)
    {
    ConfigureViewModel(model);
    return View(model);
    }
    // save and redirect
    return RedirectToAction("Somewhere");
    }

    [HttpGet]
    public JsonResult FetchCoordinates(int ID)
    {
    var data = Repository.FetchCoordinates().Where(c => c.CityID == ID).FirstOrDefault();
    return Json(data, JsonRequestBehavior.AllowGet);
    }

    [HttpGet]
    public JsonResult FetchLocalities(int ID)
    {
    var data = Repository.FetchLocalities()
    .Where(l => l.CityID == ID)
    .Select(l => new { Value = l.ID, Text = l.Name });
    return Json(data, JsonRequestBehavior.AllowGet);
    }

    [HttpGet]
    public JsonResult FetchSubLocalities(int ID)
    {
    //int localityID = Repository.FetchLocalities().Where(l => l.ID == ID).Select(l => l.LocalityID).First();
    var data = Repository.FetchSubLocalities()
    .Where(l => l.LocalityID == ID)
    .Select(l => new { Value = l.ID, Text = l.Name });
    return Json(data, JsonRequestBehavior.AllowGet);
    }

    private void ConfigureViewModel(ViewModel model)
    {
    List<City> cities = Repository.FetchCities();
    model.CityList = new SelectList(cities, "ID", "Name");
    if (model.SelectedCity.HasValue)
    {
    IEnumerable<Locality> localities = Repository.FetchLocalities().Where(l => l.CityID == model.SelectedCity.Value);
    model.LocalityList = new SelectList(localities, "ID", "Name");
    }
    else
    {
    model.LocalityList = new SelectList(Enumerable.Empty<SelectListItem>());
    }
    if (model.SelectedLocality.HasValue)
    {
    IEnumerable<SubLocality> subLocalities = Repository.FetchSubLocalities().Where(l => l.LocalityID == model.SelectedLocality.Value);
    model.SubLocalityList = new SelectList(subLocalities, "ID", "Name");
    }
    else
    {
    model.SubLocalityList = new SelectList(Enumerable.Empty<SelectListItem>());
    }
    }
    }
    }


    //////////////////////////////////////////////////////////////////////

    Code above can be viewed on dotnetfiddle [SDXNlb]

    I can't post the proper URL as I'm a new user...


  • Registered Users Posts: 17,550 ✭✭✭✭Mr. CooL ICE


    Where is the SaveResults method supposed to be?

    Also, why are you using the Index action to create a database entry? I mean, you can, but it's unintuitive. The Index action should really only display the created entries while a Create action should be used for creation.

    Also, is this due to be a single-project MVC solution?


  • Registered Users Posts: 29 MilitaryRoad


    Where is the SaveResults method supposed to be?

    Also, why are you using the Index action to create a database entry? I mean, you can, but it's unintuitive. The Index action should really only display the created entries while a Create action should be used for creation.

    Also, is this due to be a single-project MVC solution?

    Hi Mark, thanks for posting, I'm only coming back to MVC and development after an absence of a few years. I wanted a 3 layer cascading dropdown list that I could post the results to my SQL DB so I just found this particular solution and added in a SaveResults method to it at the bottom of the Home Controller code.

    Yes it's a single project solution...

    EDIT: I just put in the Index view as the return as I wanted the page to refresh after my DDL results are saved. I'm probably making a mess of how I'm doing this, I'm on the start of a learning curve with this!


  • Registered Users Posts: 29 MilitaryRoad


    Even if I just try to plonk my save code into here, its still not posting the selected items, I'm wondering am I being stupid here with what I'm trying to do or how I'm trying to do it, I mean is this feasable what I'm trying to do below? The code is posting 3 blank data fields into my DB (basically a new blank row is created on my DB table on the save button)...

    private void ConfigureViewModel(ViewModel model)
    {
    List<City> cities = Repository.FetchCities();
    model.CityList = new SelectList(cities, "ID", "Name");
    if (model.SelectedCity.HasValue)
    {
    IEnumerable<Locality> localities = Repository.FetchLocalities().Where(l => l.CityID == model.SelectedCity.Value);
    model.LocalityList = new SelectList(localities, "ID", "Name");
    }
    else
    {
    model.LocalityList = new SelectList(Enumerable.Empty<SelectListItem>());
    }
    if (model.SelectedLocality.HasValue)
    {
    IEnumerable<SubLocality> subLocalities = Repository.FetchSubLocalities().Where(l => l.LocalityID == model.SelectedLocality.Value);
    model.SubLocalityList = new SelectList(subLocalities, "ID", "Name");
    }
    else
    {
    model.SubLocalityList = new SelectList(Enumerable.Empty<SelectListItem>());
    }

    SaveResultsViewModelDBContext iDB = new SaveResultsViewModelDBContext();
    SaveResults SaveResultsDB = new SaveResults();
    SaveResults.Make = model.SelectedCity.ToString();
    SaveResults.Model = model.SelectedLocality.ToString();
    SaveResultsDB.Specification = model.SelectedSubLocality.ToString();

    iDB.SaveResultsDBs.Add(SaveResultsDB);
    iDB.SaveChanges();
    iDB.Dispose();

    }


  • Registered Users Posts: 17,550 ✭✭✭✭Mr. CooL ICE


    Hi Mark, thanks for posting, I'm only coming back to MVC and development after an absence of a few years. I wanted a 3 layer cascading dropdown list that I could post the results to my SQL DB so I just found this particular solution and added in a SaveResults method to it at the bottom of the Home Controller code.

    Yes it's a single project solution...

    EDIT: I just put in the Index view as the return as I wanted the page to refresh after my DDL results are saved. I'm probably making a mess of how I'm doing this, I'm on the start of a learning curve with this!

    I'd recommend going over something like the MS EntityFramework tutorial (here) as a means of revision. It would take less than an hour to finish and would set you on the right track.

    Your approach to the dropdowns appears to be sound from a Razor point of view, but it can't stay in the Index. Also, I think you would be better off creating an instance of the database context in your controller and inserting the code for adding/saving the database to each post method.


  • Advertisement
  • Registered Users Posts: 29 MilitaryRoad


    I'd recommend going over something like the MS EntityFramework tutorial (here) as a means of revision. It would take less than an hour to finish and would set you on the right track.

    Your approach to the dropdowns appears to be sound from a Razor point of view, but it can't stay in the Index. Also, I think you would be better off creating an instance of the database context in your controller and inserting the code for adding/saving the database to each post method.

    Thanks for getting back to me Mark, the problem seems to be that even when I put in a breakpoint when the save method is triggered, I still can’t see any values for the selected items in the dropdown fields in the home controller...


Advertisement