Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Daniel Rogers 139 posts 717 karma points
    Nov 01, 2018 @ 05:19
    Daniel Rogers
    0

    Dropdown list on change

    I have a dropdown on a partial view for a page. Its the only thing on the view.

    I have a series of other text boxes on a second partial view on the page.

    When the drop down is changed I want to load data into the text boxes form a database table.

    I can get the data from the database fine.

    What I need know is how do I initialize the onchange event and call a routine from my surface controller.

    The on change routine will need to pass a id for the record in the table.

    Can someone please point me in the right direction.

  • Alex Skrypnyk 6150 posts 24110 karma points MVP 8x admin c-trib
    Nov 01, 2018 @ 12:07
    Alex Skrypnyk
    0

    Hi Daniel

    You need angular or jQuery to make logic like that on the client side, depends on your experience and preferences.

    Alex

  • Dan Diplo 1554 posts 6205 karma points MVP 6x c-trib
    Nov 01, 2018 @ 12:11
    Dan Diplo
    1

    Ensure your dropdown is within a form that POSTS to your surface controller. Then the simplest way is to add this:

    <select onchange="this.form.submit()">
    

    This will use vanilla JS to submit the form when the dropdown changes, passing any form values to the controller.

  • Daniel Rogers 139 posts 717 karma points
    Nov 05, 2018 @ 17:03
    Daniel Rogers
    0

    Sorry dont understand

    new to this

    Searching around and trying differnet things I have this

    I have a

    @Html.DropDownListFor(x => MemberPicker.PickedItem, MemberPicker.PickerItems, new { @id = "MemberSelector", @class = "ControlList", @onchange= "/MySurfaceController/PopulateFields(1500)" })

    1500 is a interger value that should change from the drop down menu

    Generated from above

    futher down page I call PartialView with the form layout of infomation selected from value above dropdown

    @Html.Action("MemberMaintenance", "IBDMembershipFormSurface", new { NodeID = Model.Id, GlobalSettingsId = globalSettingsId })

    in my surface controller I have

    public class IBDMembershipFormSurfaceController : Umbraco.Web.Mvc.SurfaceController
    {
        IBDDropDownHelper DropDownHelper = new IBDDropDownHelper();
        IBDMembershipFormViewModel MemberForm = new IBDMembershipFormViewModel();
    
    
    
        public ActionResult MemberMaintenance(int NodeID, int GlobalSettingsID)
        {
            var DropDownModel = new IBDDropDownViewModel();
    
            MemberForm.CurrentNodeID = NodeID;
            MemberForm.GlobalSettingsID = GlobalSettingsID;
            MemberForm.MembershipTypes = DropDownHelper.GetPreValuesFromAppSettingName("IBDMembershipTypeDropDown");
    
            return PartialView("IBDMembership/IBDMembershipMaintenanceForm", MemberForm);
        }
    
        public ActionResult PopulateFields(string MemId)
        {
            var MemKey = int.Parse(MemId);
    
            IEnumerable<IBDMembershipFormViewModel> Members = GetMemberDetails(MemKey);
    
            foreach (var item in Members)
            {
                MemberForm.FName = item.FName;
                MemberForm.LName = item.LName;
                MemberForm.Position = item.Position;
            }
    
            return PartialView("IBDMembership/IBDMembershipMaintenanceForm", MemberForm);
        }
    
        public IEnumerable<IBDMembershipFormViewModel> GetMemberDetails(int MemKey)
        {
            var db = ApplicationContext.Current.DatabaseContext.Database;
            var tbl = db.Fetch<IBDMembershipFormViewModel>(@"select * from IBDMembership where MemberId=@0",MemKey);
    
            return tbl;
        }
    

    I know the populate routine works and loads data as if I call it from the MemberMaintenance routine it loads all the fields.

    I just cant get the dropdown list to call it.

  • Dan Diplo 1554 posts 6205 karma points MVP 6x c-trib
    Nov 05, 2018 @ 17:15
    Dan Diplo
    0

    You can't call server side methods from an HTML control. So your onchange event will never work - it has to call a client-side JavaScript method.

    So the below will never work:

    @Html.DropDownListFor(x => MemberPicker.PickedItem, MemberPicker.PickerItems, new { @id = "MemberSelector", @class = "ControlList", @onchange= "/MySurfaceController/PopulateFields(1500)" })
    

    As mentioned, you need to trigger the form to submit to send the values from the form to your surface controller server side, so use:

    @Html.DropDownListFor(x => MemberPicker.PickedItem, MemberPicker.PickerItems, new { id = "MemberSelector", @class = "ControlList", onchange= "this.form.submit()" })
    

    Ensure you have wrapped your controls in a FORM using something like:

    @using(Html.BeginUmbracoForm<IBDMembershipFormSurfaceController>("MemberMaintenance"))
    {
        // your form controls
    }
    

    See https://our.umbraco.com/Documentation/Reference/Templating/Mvc/Forms/tutorial-partial-views

  • Daniel Rogers 139 posts 717 karma points
    Nov 12, 2018 @ 13:54
    Daniel Rogers
    0

    All this does is refreshes the screen back to the start. Doesn't call the routine PopulateFields. Doesn't keep the selected value in the dropdown box.

  • Daniel Rogers 139 posts 717 karma points
    Nov 06, 2018 @ 05:27
    Daniel Rogers
    0

    So I are getting closer. (Why is my answer in green this is not solved)

    When I change my dropdown menu it refreshes the whole page. Which means we end up back at the beginning. ie first member .

    What I think should happen (want to happen) is when the dropdown is changed the MemberForm model is loaded with new variables and the boxes change without refreshing the screen as that is unnecessary wast of time to the end user.

    Once I have this working the I also need to be able to test that data is saved to database else flag a question to save or continue and disregard changes. This may change how this onchange is achieved.

    How do I pass the int value from the (database Key) dropdown to the PopulateFields routine.

    FYI calling MemberMaintanance() routine has same affect.

    Partial View for page content

    @inherits UmbracoViewPage

    @using USN.USNTemplate; @using IBD.IBDModels; @using IBD.IBDHelper; @using IBD.IBDControllers;

    @using USNOptions = USNStarterKit.USNEnums.Options;

    @using (Html.BeginUmbracoForm

    MemberPicker.PickerItems = DropDownHelper.BuildMembersDropDown();
    

    ......... Does some other stuff ..............

    <div class="form-side @animateClass" data-os-animation="@formFadeInDirection" data-os-animation-delay="0">
        <div class="inner c5-bg base-text has-borders c6-borders">
            <div id="MemberContainer">
                <label for="MemberSelect"><strong>Sellect Member To Edit...</strong></label>
                @Html.DropDownListFor(x => MemberPicker.PickedItem, MemberPicker.PickerItems,
                                                         new { @id = "MemberSelect", @class = "ControlList", onchange= "this.form.submit()" })
            </Div>
        </div>
    </div>
    

    ......... Does some other stuff ..............

    // This section displays data related to member selected above.

    <section id="MemberDetails" class="content apc text-with-form @settings.BackGroundStyle @Model.CustomComponentClasses" @Html.Raw(backgroundImageStyle) id="[email protected]">
        <div class="container">
            <!-- ROW -->
            <div class="row">
                <div class="Membership form ajax-wrap">
                    <div class="inner c5-bg base-text has-borders c6-borders">
                            @Html.Action("MemberMaintenance", "IBDMembershipFormSurface", new { NodeID = Model.Id, GlobalSettingsId = globalSettingsId })
                    </div>
                </div>
            </div>
        </div>
    </section>
    

    }

    I are calling this routine as I only thought it would only load the data related to the model rather than the whole partial view.

    The model holds the variables for the text boxes in the patial view.

    PopulateFields(int MemKey) Controller routine has changed from above

        public ActionResult PopulateFields(int MemKey)
        {
            IEnumerable<IBDMembershipFormViewModel> Members = GetMemberDetails(MemKey);
    
            foreach (var item in Members)
            {
                MemberForm.FName = item.FName;
                MemberForm.LName = item.LName;
                MemberForm.Position = item.Position;
            }
    
            return RedirectToCurrentUmbracoPage();
        }
    

    Screen shot of from

  • Dan Diplo 1554 posts 6205 karma points MVP 6x c-trib
    Nov 06, 2018 @ 08:52
    Dan Diplo
    0

    To make the form submit without refreshing the page you are going to have to use AJAX (ie. client-side JavaScript that calls server functions). This is too big a subject to really cover here and if I where you I'd work on getting the form to work without AJAX first - a page reload isn't necessarily a bad thing as it allows you to update state, display messages etc.

    If you really want to get into AJAX then maybe check out this:

    https://codeshare.co.uk/blog/how-to-change-a-form-in-mvc-to-submit-with-ajax/

  • Daniel Rogers 139 posts 717 karma points
    Nov 13, 2018 @ 14:21
    Daniel Rogers
    0

    Ok so I have done some reasearch on JQuery and server side acceess.

    And have got this.

    asmx.cs server file

    using System.Web.Services;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    
    
    
    namespace IBDMemberManager
    {
        /// <summary>
        /// Summary description for MemberService
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [System.Web.Script.Services.ScriptService]
    
        public class MemberService : System.Web.Services.WebService
        {
    
            [WebMethod]
            public MemberDetails GetMemberByID(int MemId)
            {
                MemberDetails Member = new MemberDetails();
    
                string cs = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("spGetMemberById", con);
                    cmd.CommandType = CommandType.StoredProcedure;
    
                    SqlParameter parameter = new SqlParameter();
                    parameter.ParameterName = "@Id";
                    parameter.Value = MemId;
    
                    cmd.Parameters.Add(parameter);
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        Member.FName = rdr["FName"].ToString();
                        Member.LName = rdr["LName"].ToString();
                        Member.Position = rdr["Position"].ToString();
                    }
                }
    
                return Member;
            }
        }
    }
    

    script

    <script type="text/javascript">
        $(document).ready(function () {
            $('#MemberSelect').change(function () {
                var MemId = $('#MemberSelect').val();
                $.ajax({
                    url: "MemberService.asmx/spGetMemberById",
                    data: { MemberId: MemId },
                    method: 'post',
                    dataType: 'xml',
                    successs: function (data) {
                        var jqueryXml = $(data);
                        $('#FirstName').Val(jquaryXml.find('FName').text());
    
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            });
        });
    </script>
    

    my drop down

                @Html.DropDownListFor(x => MemberPicker.PickedItem, MemberPicker.PickerItems, new { @id = "MemberSelect", @class = "ControlList" })
    

    But I get a Localhost says [object Object]

    From what I can make out It must be something to do with this line var jqueryXml = $(data); but Im not sure what I have wrong.

  • Daniel Rogers 139 posts 717 karma points
    Nov 16, 2018 @ 13:59
    Daniel Rogers
    0

    Got this work except I need to pass some extra variables to the partial view

    j script looks like this.

    <script scr="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#MemberSelect').change(function () {
                var MemberId = $('#MemberSelect').val();
                $('#MemberDetails').load('@Url.Action("MemberMaintenance", "IBDMembershipFormSurface")' + '?MemId=' + MemberId + '?NodeID =' + Model.Id + '?GlobalSettingsID =' + globalSettingsId)
            });
        });
    </script>
    

    GlobalSettingsID abd NodeID are the extra 2 variables if I remove these the form reloads except I need to remove some other code in the function.

    These variables are declared

    Model.Id is the ID of the form model

    and

    int globalSettingsId = Convert.ToInt32(ViewData["globalSettingsID"]); 
    

    Any Surgestions.

    The HTML code further down the page is

    <div class="row">
        <div class="form-side @animateClass" data-os-animation="@formFadeInDirection" data-os-animation-delay="0">
            <section id="MemberDetails" class="content apc text-with-form @settings.BackGroundStyle @Model.CustomComponentClasses" @Html.Raw(backgroundImageStyle) id="[email protected]">
                @Html.Action("MemberMaintenance", "IBDMembershipFormSurface", new { @id = "MemberDetails", MemId = 1485, NodeID = Model.Id, GlobalSettingsID = globalSettingsId } )
            </section>
        </div> 
    </div>
    
  • Daniel Rogers 139 posts 717 karma points
    Nov 21, 2018 @ 13:11
    Daniel Rogers
    0

    solved

    <script scr="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#MemberSelect').change(function () {
                var PreviousId = $('#MemberSelect').val();
                var MemberId = $('#MemberSelect').val();
                var MId = @Html.Raw(Json.Encode(Model.Id));
                //var GId = $('#globalSettingsId').val();
                $('#MemberDetails').load('@Url.Action("MemberMaintenance", "IBDMembershipFormSurface")' + '?MemId=' + MemberId + '&NodeID=' + MId); // + '&GlobalSettingsID=' + GId);
            });
        });
    </script>
    
Please Sign in or register to post replies

Write your reply to:

Draft