This is a migrated thread and some comments may be shown as answers.

Set selected item in ddl using ajax binding with value from model

5 Answers 276 Views
DropDownList
This is a migrated thread and some comments may be shown as answers.
Donna Stewart
Top achievements
Rank 1
Donna Stewart asked on 17 Mar 2014, 08:18 PM
I have a popup window to be used for editing detailed information of a row in a grid.  The popup window's content is from a partial view.  In this popup window I have a dropdownlist for states.  This custom popup edit window is opened when a custom command button is clicked.  I call an action on the controller to pull the data to populate the custom popup, I put that data in a model and I have the custom popup using the model.  Everything works fine, except the dropdownlist's selected value is not set.  It just shows the first item in the list.  I've tried setting the .Value option to the model value - .Value(Model.state) - doesn't work.  I've tried using the DataBound event to set the value there to the model.State, but I get errors.  If I try to declare the event function in the popup partial view, it doesn't get recognized and I get the not declared error.  If I try to declare it in the calling view, it doesn't recognize the model (since it's in the partial view).  What am I doing wrong?  Any help is very much appreciated!

Here's the code:
 
Calling view (Index.cshtml) - grid and popup window:
@model IEnumerable<GMCEventRegistrationTools.Models.EventRegistrationModel>
                    @(Html.Kendo().Grid<GMCEventRegistrationTools.Models.EventRegistrationModel>()
                        .Name("EventRegistrationGrid")
                        .AutoBind(false)
                        .ToolBar(toolbar => toolbar.Create())
                        .Editable(editable => editable.Mode(GridEditMode.InLine))
                        .DataSource(dataSource => dataSource
                            .Ajax()
                            .Model(model => model.Id(p => p.RegistrationKey))
                            .Read(read => read.Action("Registrants_Read", "Home").Data("registrantsForEvent"))
                            .Create(update => update.Action("EditingPopup_Create", "Home"))
                            .Update(update => update.Action("EditingPopup_Update", "Home"))
                            .Destroy(update => update.Action("EditingPopup_Destroy", "Home"))
                        )
                        .Columns(cols =>
                            {
                                cols.Bound(p => p.RegistrationKey).Hidden(true);
                                cols.Bound(p => p.FirstName);
                                cols.Bound(p => p.LastName);
                                cols.Bound(p => p.CompanyName);
                                cols.Bound(p => p.ProvideAccomodations);
                                cols.Bound(p => p.RegistrationConfirmed);
                                cols.Command(command => { command.Edit(); command.Destroy(); });
                                cols.Command(command => command.Custom("Edit Details").Click("editDetails"));
                            }
                        )
                        .ClientDetailTemplateId("registration-client-template")
                    )
 
    @(Html.Kendo().Window().Name("EditRegDetails")
        .Title("Edit Registration")
        .Visible(false)
        .Modal(true)
        .Draggable(true)
        .Width(900)
    )
 
    function editDetails(e) {
        e.preventDefault();
        var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        var window = $("#EditRegDetails").data("kendoWindow");
        window.refresh({
            url: '/Home/GetRegistrationDetails',
            data: { id: dataItem.RegistrationKey }
        });
        window.center();
        window.open();
    }
 
Controller/Action:
        public ActionResult GetRegistrationDetails(int id)
        {
            EventRegistrationModel eRegistrationModel = new EventRegistrationModel();
            using (var eventTools = new WebDBEntities())
            {
                WebEventRegistration reg = eventTools.WebEventRegistrations.Where(p => p.RegistrationKey == id).FirstOrDefault();
                AdditionalInfo ai = new AdditionalInfo();
                var serializer = new JavaScriptSerializer();
                if (reg != null && (reg.FirstName != null && reg.FirstName != ""))
                {
                    eRegistrationModel.AddressLine1 = reg.AddressLine1;
                    eRegistrationModel.AddressLine2 = reg.AddressLine2;
                    eRegistrationModel.City = reg.City;
                    eRegistrationModel.CompanyName = reg.CompanyName;
                    eRegistrationModel.EmailAddress = reg.EmailAddress;
                    eRegistrationModel.EventDetails = serializer.Deserialize<AdditionalInfo>(reg.EventDetails);
                    eRegistrationModel.EventName = reg.EventName;
                    eRegistrationModel.FirstName = reg.FirstName;
                    eRegistrationModel.JobTitle = reg.JobTitle;
                    eRegistrationModel.LastName = reg.LastName;
                    eRegistrationModel.MiddileInitial = reg.MiddileInitial;
                    eRegistrationModel.PhoneNumber = reg.PhoneNumber;
                    eRegistrationModel.PostalCode = reg.PostalCode;
                    eRegistrationModel.ProvideAccomodations = reg.ProvideAccomodations == 0 ? true : false;
                    eRegistrationModel.ReferrerIpAddress = reg.ReferrerIpAddress;
                    eRegistrationModel.RegistrationConfirmed = reg.RegistrationConfirmed == 0 ? true : false;
                    eRegistrationModel.RegistrationDate = reg.RegistrationDate;
                    eRegistrationModel.State = reg.State;
                    eRegistrationModel.RegistrationKey = reg.RegistrationKey;
                }
                else
                {
                    return View("Error");
                }
            }
            return PartialView("EditRegistrationDetails", eRegistrationModel);
        }
 
Partial view with dropdown:
@model GMCEventRegistrationTools.Models.EventRegistrationModel
 
        @using (Html.BeginForm("SaveRegistrationEdit", "Home", FormMethod.Post, new { id = "editregis-form" }))
        {
most fields removed for brevity
                        <div class="form-group">
                            @Html.LabelFor(model => model.State)
                            @(Html.Kendo().DropDownListFor(model => model.State).Name("State")
                            .HtmlAttributes(new { @class = "form-control textbox-size stateslist"})
                            .DataTextField("State").DataValueField("StateCode")
                            .DataSource(source => {
                                source.Read(read =>
                                {
                                    read.Action("GetStates", "Home");
                                });
                            })
                            .Value(Model.State)
                            .Events(events => events.DataBound("setSelectedState"))
                            )
                            <p class="error">@Html.ValidationMessageFor(model => model.State)</p>
                        </div>

Thanks!
Donna



5 Answers, 1 is accepted

Sort by
0
Petur Subev
Telerik team
answered on 19 Mar 2014, 01:49 PM
Hello Donna,

You should set the StatusCode as value - the value is compared to the DataValueField that you specified for the DropDownList. If still struggling send a demo project so we can investigate what exactly goes wrong.

Kind Regards,
Petur Subev
Telerik
 

DevCraft Q1'14 is here! Watch the online conference to see how this release solves your top-5 .NET challenges. Watch on demand now.

 
0
Donna Stewart
Top achievements
Rank 1
answered on 19 Mar 2014, 06:29 PM

Hi Petur,

Thank you for your response.  Did you mean StateCode instead of StatusCode?  That threw me off for a minute...

 My dropdownlist is being populated by the Read, which is pulling the list of states from a database table.  In that list, the State field is the long state name like Tennessee and the StateCode is the abbreviation, i.e., TN.  In the model, the abbreviation is what is stored iin the State field.  So, I want the selected item or index to be set to what the State field value is in the model when this window pops up.  I'm not sure how to do this.  I have just noticed that if I close the popup and reopen it, the State field becomes just an input field and it has the correct state value.  The script code is still there for the dropdownlist, but the dropdownlist does not show.  I have attached screen shots.

Here is just the code for the dropdownlist:
@(Html.Kendo().DropDownListFor(model => model.State).Name("State")
.HtmlAttributes(new { @class = "form-control textbox-size stateslist"})
.DataTextField("State").DataValueField("StateCode")
.DataSource(source => {
    source.Read(read =>
    {
        read.Action("GetStates", "Home");
    });
})
.Value(Model.State)
)

Here is the code in the controller for the read.Action:
public JsonResult GetStates()
{
    var FedExEnts = new FedExEntities();
    var states = FedExEnts.GetStateList("US").AsQueryable();
    return Json(states.Select(p => new { State = p.State, StateCode = p.State_Abbr }), JsonRequestBehavior.AllowGet);
}

Here is the model:
public class EventRegistrationModel
{
    public int RegistrationKey { get; set; } // Registration_Key (Primary key)
    public DateTime RegistrationDate { get; set; } // Registration_Date
    public string EventName { get; set; } // Event_Name
    public string LastName { get; set; } // Last_Name
    public string FirstName { get; set; } // First_Name
    public string MiddileInitial { get; set; } // Middile_Initial
    public string CompanyName { get; set; } // Company_Name
    public string EmailAddress { get; set; } // Email_Address
    public string AddressLine1 { get; set; } // Address_Line1
    public string AddressLine2 { get; set; } // Address_Line2
    public string City { get; set; } // City
    public string State { get; set; } // State
    public string PostalCode { get; set; } // Postal_Code
    public string PhoneNumber { get; set; } // Phone_Number
    public string JobTitle { get; set; } // Job_Title
    public bool ProvideAccomodations { get; set; } // Provide_Accomodations
    public bool RegistrationConfirmed { get; set; } // Registration_Confirmed
    public string ReferrerIpAddress { get; set; } // ReferrerIPAddress
    public AdditionalInfo EventDetails { get; set; } // Event_Details
}

0
Petur Subev
Telerik team
answered on 21 Mar 2014, 12:15 PM
Hello Donna,

Indeed what I meant to write is StateCode. However the code that you shared looks all fine (to make the Grid select an item from the list you should either use the Value method or the SelectIndex method), could you please clarify if that DropDownList isn't actually used as an Editor For the Grid? From what you shared it looks like you are using it on a separate view not related to the Grid widget, is that right?

In order to troubleshoot the case faster, could you send us some small demo project which we can run and see what exactly fails?

Kind Regards,
Petur Subev
Telerik
 

Build cross-platform mobile apps using Visual Studio and .NET. Register for the online webinar on 03/27/2014, 11:00AM US ET.. Seats are limited.

 
0
Donna Stewart
Top achievements
Rank 1
answered on 21 Mar 2014, 09:12 PM
You are right, I am using a separate view for the Edit Details (which is a custom command on the grid in the Index.cshtml).  When that button is clicked on the grid, I make a call back to the Controller to get the details for the key of the row on which the button was clicked.  Then I have a Kendo window that opens to show the detail data for the user to edit.  This uses a partial view.  This partial view is where the dropdownlist is.  I created a demo project in which I stripped some things out and created xml files for the data that I grab from the database.  Of course, Murphy's Law, this demo project works perfectly!  I have looked and looked and tried different things to figure out why the demo works, but my real app doesn't.  I have attached screen shots of running the app in Page Inspector.  You will see the Kendo window of each and the rendered html below.  To me, the rendered html looks pratically identical, so I am completely at a loss as to why my real app won't work.  Maybe you guys can see something?!  Hopefully!!  I tried to attach a zip file of the demo project I created, but it's too large.

Thanks so much for your time and help!
Donna
0
Petur Subev
Telerik team
answered on 25 Mar 2014, 11:32 AM
Hello Donna,

If the sample project does not reproduce the problem it wont help us determine the problem. Could you give us some live URL which we can use to visit a running app. We will do our best to see where the problem is coming from.

Also could you try to clear the ModelState before doing anything inside the action method that serves the partial view?

ViewData.ModelState.Clear()

It might be related.

Kind Regards,
Petur Subev
Telerik
 

Build cross-platform mobile apps using Visual Studio and .NET. Register for the online webinar on 03/27/2014, 11:00AM US ET.. Seats are limited.

 
Tags
DropDownList
Asked by
Donna Stewart
Top achievements
Rank 1
Answers by
Petur Subev
Telerik team
Donna Stewart
Top achievements
Rank 1
Share this question
or