2

vs'12 , KendoUI, asp.net C# MVC4 Internet Application EF Code First

Would like to see how one would pass values form a KendoUI DropDownList to a MVC Controller from a Razor View

Controller

  [HttpPost]
  //[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(ViewModelCCTRST model) //, FormCollection  values)
    {

        if (ModelState.IsValid)
        {

            string clt = model.Clients;
            string cnt = model.Countys;
            string twn = model.TownShips;
            ...
             ...
            //string xx = values["Clients"];
            //       xx = values["Countys"];
            //       xx = values["TownShips"];
                     ...
                      ...

*clt,cnt,twn and other variables are always null... wherein lies my question why are these always null**


Razor View:

                @ @(Html.Kendo().DropDownListFor(m=>m.Ranges)
                      //.Name("ranges")
                      .HtmlAttributes(new { style = "width:300px"}) //, id = "ranges"})
                      .OptionLabel("Select Range...")
                      .DataTextField("RangeName")
                      .DataValueField("RangeID")
                      .DataSource(source => {
                          source.Read(read =>
                          {
                              read.Action("GetCascadeRanges", "AddCCCTRST")
                                  .Data("filterRanges");
                          })
                          .ServerFiltering(true);
                      })
                      .Enable(false)
                      .AutoBind(false)
                      .CascadeFrom("TownShips")
                )
                <script>
                    function filterRanges() {
                        return {
                            townShips: $("#TownShips").val()
                        };
                    }

Things i have tried

  • setting var text = dropdownlist.text();
  • setting var DDLtracts = $("#tracts").data("kendoDropDownList");

No matter what i try id wise or controller wise I cannot get the values to be "Read" in the Controller, nor can i grab and pass the values on in action links.

Please help!!


Updated Code Per Comments by mmillican help below

                string sct = model.Sections;
                string trt = model.Tracts;

Viewmodel

public class ViewModelCCTRST
{
    public string Clients { get; set; }
    public IEnumerable<dbClient> AvailableClients { get; set; }
    public string Countys { get; set; }
    public IEnumerable<dbCounty> AvailableCounties { get; set; }
    public string TownShips { get; set; }
    public IEnumerable<dbTownShip> AvailableTownShip { get; set; }
    public string Ranges { get; set; }
    public IEnumerable<dbRange> AvailableRanges { get; set; }
    public string Sections { get; set; }
    public IEnumerable<dbSection> AvailableSection { get; set; }
    public string Tracts { get; set; }
    public IEnumerable<dbTract> AvailableTracts { get; set; }
}

What we have done so far is:

  • Removed [AcceptVerbs(HttpVerbs.Post)] and FormCollection values from controller
  • Removed //.Name("Tracts") and optional .HtmlAttributes(new { id = "tracts"}) from each DropDownList
  • Added DropDownListFor(m=>m.Tracts) for each DDL and imported @model OG.ModelView.ViewModelCCTRST CustomViewModel can be read below
  • Renamed all lowercase .CascadeFrom("clients") (not just clients) to uppercase .CascadeFrom("Clients")

The tag below where it says alert("Select Tract to Upload:\n....); did actually alert 1 time during these changes, however the Model and variable attempting to send with an Actionlink form the Razor View are still both null and the alert stopped popping up.

    $(document).ready(function () {
        $("#get").click(function () {
            var clients = $("#Clients").data("kendoDropDownList"),
            countys = $("#Countys").data("kendoDropDownList"),
            TownShip = $("#TownShip").data("kendoDropDownList"),
            ranges = $("#Ranges").data("kendoDropDownList"),
            sections = $("#Sections").data("kendoDropDownList"),
            tracts = $("#Tracts").data("kendoDropDownList");

      var clientsInfo = "\nclients: { id: " + clients.value() + ", name: " + clients.text() + " }",
      countysInfo = "\ncountys: { id: " + countys.value() + ", name: " + countys.text() + " }",
       ....
        ....

      alert("Select Tract To Upload:\n" + clientsInfo + countysInfo + townShipsInfo + rangesInfo + sectionsInfo + tractsInfo);
           });
    });

Update

fixed syntax issue fixed the scipt error. Is now populating clientsInfo + countysInfo + townShipsInfo + rangesInfo + sectionsInfo + tractsInfo - does this help anyone help me get this to my controller?

asdf

Don Thomas Boyle
  • 3,055
  • 3
  • 32
  • 54
  • 1
    Be mindful of your commas and lack of semi-colons. You're creating a variable named 'alert' - confusing the compiler. That leads to all sorts of bugs. – Brett Aug 26 '13 at 23:56
  • @Brett thanks for catching that! – Don Thomas Boyle Aug 27 '13 at 14:47
  • Bump, any other ideas? – Don Thomas Boyle Aug 28 '13 at 12:56
  • To get that data to the controller, a simple way would be to stringify it and send it via an ajax POST. You don't have your HTML markup pasted, so I don't know how you're doing it now - whether in a form submit or via ajax. `$.ajax({ url: 'http://localhost//', data: JSON.stringify({ clients: {...}, countys: {...}, etc. }), type: 'POST', contentType: 'application/json' });` – Brett Aug 28 '13 at 13:48

1 Answers1

2

You should use a ViewModel that has your properties in it such as:

Updated

public class MyViewModel
{
    public string Clients { get; set; }
    public IEnumerable<Client> AvailableClients { get; set; }
    public string Countys { get; set; }
    public IEnumerable<Client> AvailableCounties { get; set; }
    public string TownShips { get; set; }
    public IEnumerable<Client> AvailableTownShips { get; set; }
    public string Sections { get; set; }
    public IEnumerable<Client> AvailableSection { get; set; }
    public string Tracts { get; set; }
    public IEnumerable<Tract> AvailableTracts { get; set; }
}

Then your Kendo DropDownList would become a DropDownListFor<> as shown here:

@(Html.Kendo().DropDownListFor(m => m.Clients)
                  .HtmlAttributes(new { style = "width:300px"}) //, id = "clients"})
                  .OptionLabel("Select Client...")
                  .DataTextField("ClientName")
                  .DataValueField("ClientID")
                  .DataSource(source => {
                       source.Read(read => {
                           read.Action("GetCascadeClients", "ImageUpload");
                       });
                  })
                 ***1***
            )

And you can then post to your controller in the following way:

[HttpPost]
    public ActionResult Index(MyViewModel model)
    {

        if (ModelState.IsValid)
        {

            var newVar = model.Clients;

When you return the ViewModel to the View (from the Controller) and MyViewModel.Clients has the value "Client1", the DropDownList will pick that up and have it be the selected value.

Hopefully this is what you're looking for / makes sense.

Matt Millican
  • 4,044
  • 4
  • 38
  • 55
  • Makes sence and will be trying it out here shortly, the clients, countys, townships are Full models however, won't i need an Icollection of Clients in my ViewModel - I do apologize about the offtopic question this will be my first ViewModel to create. – Don Thomas Boyle Aug 27 '13 at 12:47
  • 1
    In that case, yes. I will update my answer with something that should help you. Let me know if you need more assistance. – Matt Millican Aug 27 '13 at 12:51
  • 1
    I added some properties to the ViewModel that I think are what you're asking for. However, now that I think about it, you're using AJAX bindings so you probably wouldn't need those. If you don't want to use AJAX bindings you could add `.BindTo(Model.AvailableClients)` in your `DropDownListFor<>` however that wouldn't work for cascading drop downs. – Matt Millican Aug 27 '13 at 12:55
  • Thanks for the update. There Json Binding if that matters at all, will implement the Viewmodel with the Json Binding then. – Don Thomas Boyle Aug 27 '13 at 12:57
  • That should work for what you need then I believe. Let me know if not. – Matt Millican Aug 27 '13 at 12:58
  • Sorry I'm having issues resolving a "I created a folder but it won't let me import `@model OG.foldername`, so as soon as i figure that out ill get back with you if you answer worked. – Don Thomas Boyle Aug 27 '13 at 13:09
  • Ok heres a question for you, why must i Import the new ViewModel like `@model IEnumerable` instead of `@model OG.ModelView.ViewModelCCTRST` ?? One gives me an error ( 2nd ) the other (first) won't let me use your `().DropDownlistFor(m=>m.Clients)` Approach – Don Thomas Boyle Aug 27 '13 at 13:40
  • That would depend on exactly what you were trying to do in your View. I believe you would want to use the 2nd approach, but is out of the scope of this question (for keeping SO clean). – Matt Millican Aug 27 '13 at 13:58
  • That was my mistake, imported it incorrectly with ";" behind the import. Ill re-post my code above in an Edit - variables are still null in the controller – Don Thomas Boyle Aug 27 '13 at 14:16
  • 1
    Try getting rid of the `.Name("sections")` on your DropDownLists – Matt Millican Aug 27 '13 at 14:31
  • tryed that the – Don Thomas Boyle Aug 27 '13 at 14:33
  • I was able to change `.Name("sections")` to `.HtmlAttributes(new { style = "width:300px", id = "sections"})` without altering the Json functionality. However still no data in my controller. – Don Thomas Boyle Aug 27 '13 at 14:41
  • 1
    Strange. Try removing the `FormCollection values` param from the POST ActionMethod. Also, the `[AcceptVerbs(HttpVerbs.Post)]` is redundant and can be removed. – Matt Millican Aug 27 '13 at 14:50
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/36339/discussion-between-don-thomas-boyle-and-mmillican) – Don Thomas Boyle Aug 27 '13 at 14:59
  • updated the question as discussed in the private chat. Thanks again for your help sofar. – Don Thomas Boyle Aug 27 '13 at 16:30
  • just btw you don't happen to have code for a Control / View of just 2 DDL's that are Cascading working do you? - If you do maybe I can just model mine after that? – Don Thomas Boyle Aug 28 '13 at 12:59
  • Unfortunately I don't. I've only done cascading with the MultiSelect, which isn't supported out of the box, but I developed a workaround for as detailed here: http://www.mattmillican.com/cascding-mutliselect-with-kendo-ui-mvc – Matt Millican Aug 28 '13 at 15:10
  • Answer actually much simpler then we were attempting, the KendoUI DropDownLists were NOT in a , therefore didn't return values. All the help from @mmillican reformed and made the code work. Thanks again for your time. – Don Thomas Boyle Aug 28 '13 at 16:26