logo
down
shadow

Getting current stored value from database in a form on Cascading dropdowns in edit mode C# MVC


Getting current stored value from database in a form on Cascading dropdowns in edit mode C# MVC

By : user2172717
Date : October 22 2020, 08:10 PM
seems to work fine Through much research and I am still not completely sure that this is the proper way to do this, but it works. So if you are in need of a cascading dropdown with edit this is the way I have done it.
I will start with the view model.
code :
    public class EditAddressViewModel
    {
    public Guid AddressUI { get; set; }

    [Display(Name = "Billing Address?")]
    [UIHint("_IsStatus")]
    public bool IsBilling { get; set; }

    [Display(Name = "Shipping Address?")]
    [UIHint("_IsStatus")]
    public bool IsShipping { get; set; }

    [Display(Name = "Location Name")]
    [Required(ErrorMessage = "Location name is required")]
    public string LocationName { get; set; }

    [Display(Name = "Contact Name")]
    [Required(ErrorMessage = "Contact name is required")]
    public string ContactName { get; set; }

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

    [Display(Name = "Address 2")]
    [Required(ErrorMessage = "Address line 2 is required - Should be your address or PO Box")]
    public string Line2 { get; set; }

    [Display(Name = "Country")]
    [Required(ErrorMessage = "Country name is required")]
    public int Country { get; set; }
    public IEnumerable<SelectListItem> Countries { get; set; }

    [Display(Name = "State")]
    [Required(ErrorMessage = "State name is required")]
    public int State { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }

    [Display(Name = "City")]
    [Required(ErrorMessage = "City name is required")]
    public int City { get; set; }
    public IEnumerable<SelectListItem> Cities { get; set; }

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

    [Display(Name = "Contact Email")]
    [Required(ErrorMessage = "Email contact is required")]
    [DataType(DataType.EmailAddress)]
    [StringLength(320)]
    [RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", ErrorMessage = "Enter a valid email address")]
    public string EmailAddress { get; set; }

    [Display(Name = "Phone Number")]
    [Required(ErrorMessage = "Phone number is required")]
    [DataType(DataType.PhoneNumber)]
    [StringLength(12)]
    [RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", ErrorMessage = "Enter a valid phone number")]
    public string PhoneNumber { get; set; }

    [Display(Name = "Fax Number")]
    [DataType(DataType.PhoneNumber)]
    [StringLength(12)]
    [RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", ErrorMessage = "Enter a valid phone number")]
    public string FaxNumber { get; set; }

    public int CompanyId { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}", ApplyFormatInEditMode = false)]
    public DateTime CreatedDate { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}", ApplyFormatInEditMode = false)]
    public DateTime LastUpdated { get; set; }

}
    // Customer Input
    // GET: Addresses/Edit?guid=56A792FE-28D1-4D1D-8F59-21DE1EABA2FB
    // TO DO - Create Route in APP_Start RouteConfig for better looking link.
    [Authorize(Roles = "CompanyAdmin")]
    public ActionResult UserEditAddress(Guid guid)
    {
        if (guid == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        AddressEdit addresses = db.AddressEdit.Find(guid);
        if (addresses == null)
        {
            return HttpNotFound();
        }
        var model = new EditAddressViewModel();
        model.AddressUI = addresses.AddressUI;
        model.Line1 = addresses.Line1;
        model.Line2 = addresses.Line2;
        model.Country = addresses.Country;
        model.State = addresses.State;
        model.City = addresses.City;
        model.ZipCode = addresses.ZipCode;
        model.Countries = new SelectList(db.Countries, "CountryId", "CountryName", addresses.Country);
        model.States = new SelectList(db.States, "StateId", "StateName", addresses.State);
        model.Cities = new SelectList(db.Cities, "CityId", "CityName", addresses.City);

        return View(model);
    }

    // POST: Addresses/Edit?guid=56A792FE-28D1-4D1D-8F59-21DE1EABA2FB
    // TO DO - Create Route in APP_Start RouteConfig for better looking link.
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UserEditAddress([Bind(Include = "AddressUI,Line1,Line2,Country,State,City,ZipCode,CompanyId")] AddressEdit addresses)
    {
        var userId = User.Identity.GetUserId();
        if (ModelState.IsValid)
        { 
            db.Entry(addresses).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index", "Customer", new { UserId = userId });
        }

        return View(addresses);
    }

    // Get States
    public JsonResult GetStates(string countryId)
    {
        int Id;
        Id = Convert.ToInt32(countryId);

        var states = from a in db.States where a.CountryId == Id select a;
        return Json(states);

    }


    // Get Cities
    public JsonResult GetCities(string stateId)
    {
        int Id;
        Id = Convert.ToInt32(stateId);

        var cities = from a in db.Cities where a.StateId == Id select a;
        return Json(cities);
    }
namespace MyProject.BusinessModels.Entities
{
    public class AddressEdit
    {
    [Key]
    public Guid AddressUI { get; set; }
    [Display(Name = "Address")]
    public string Line1 { get; set; }
    [Display(Name = "Address 2")]
    public string Line2 { get; set; }
    [Display(Name = "Country")]
    public int Country { get; set; }
    [Display(Name = "State")]
    public int State { get; set; }
    [Display(Name = "City")]
    public int City { get; set; }
    [Display(Name = "ZipCode")]
    public string ZipCode { get; set; }
    }
}
@model MyProject.Models.EditAddressViewModel
@using Microsoft.AspNet.Identity
@{
ViewBag.Title = "UserEdit";
Layout = "~/Views/Shared/CustomerDashboardLayout.cshtml";
}

<br />

<div class="row">
    <div class="col-lg-12">
        <p>
            @{ var userId = User.Identity.GetUserId(); }

            @Html.ActionLink("Back to List", "Index", "Customer", new { UserId = userId }, new { @class = "btn btn-primary" })
        </p>
    </div>
    <!-- /.col-lg-12 -->
</div>
<div class="row">
    <div class="col-lg-6">
        <div class="tile">
            <h3 class="tile-title">Edit Address</h3>
            <div class="tile-body">
                @using (Html.BeginForm())
                {
                    @Html.AntiForgeryToken()

                <div class="form-horizontal">

                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    @Html.HiddenFor(model => model.AddressUI)

                    <div class="form-group row">
                        @Html.LabelFor(model => model.Line1, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-8">
                            @Html.EditorFor(model => model.Line1, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Line1, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group row">
                        @Html.LabelFor(model => model.Line2, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-8">
                            @Html.EditorFor(model => model.Line2, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Line2, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group row">
                        @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-8">
                            @Html.DropDownListFor(model => Model.Country, Model.Countries, "Select Country", new { @class = "form-control", @id = "ddlCountry" })
                            @Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group row">
                        @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-8">
                            @Html.DropDownListFor(model => model.State, Model.States, "Select State", new { @class = "form-control", @id = "ddlState" })
                            @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group row">
                        @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-8">

                            @Html.DropDownListFor(model => model.City, Model.Cities, "Select City", new { @class = "form-control", @id = "ddlCity" })
                            @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group row">
                        @Html.LabelFor(model => model.ZipCode, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-8">
                            @Html.EditorFor(model => model.ZipCode, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.ZipCode, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="tile-footer">
                        <div class="row">
                            <div class="col-md-8 col-md-offset-3">
                                <input type="button" id="btnReset" value="Reset" onclick="Reset();" class="btn btn-default" />
                                <input type="submit" value="Save" class="btn btn-primary" />
                            </div>
                        </div>
                    </div>
                </div>
                }

            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    function Reset() {
        document.getElementById('ddlCountry').selectedIndex = 0;
        document.getElementById('ddlState').innerHTML = "";
        document.getElementById('ddlCity').innerHTML = "";


        $(function () {
            $('#ddlCountry').change(function () {
                $.ajax({
                    type: "post",
                    url: "/Addresses/GetStates",
                    data: { countryId: $('#ddlCountry').val() },
                    datatype: "json",
                    traditional: true,
                    error: function (_, err) {
                        console.log(_, err)
                    },
                    success: function (data) {
                        $.each(data, function (index, value) {
                            $('#ddlState').append('<option value="' + value.StateId + '">' + value.StateName + '</option>');
                        });
                    }
                });
            });

            $('#ddlState').change(function () {
                $.ajax({
                    type: "post",
                    url: "/Addresses/GetCities",
                    data: { stateId: $('#ddlState').val() },
                    datatype: "json",
                    traditional: true,
                    error: function (_, err) {
                        console.log(_, err)
                    },
                    success: function (data) {
                        $.each(data, function (index, value) {
                            $('#ddlCity').append('<option value="' + value.CityId + '">' + value.CityName + '</option>');
                        });
                    }
                });
            });
        });
    }

</script>


Share : facebook icon twitter icon
Repopulate cascading dropdownlist in edit mode - MVC

Repopulate cascading dropdownlist in edit mode - MVC


By : Ionel Dobroiu
Date : March 29 2020, 07:55 AM
I wish this help you Finally got my cascading dropdownlist working only to find it's not repopulating in edit mode. The first dropdownlist populates, and I've set the jquery to run on either the dropdown change, or the document ready. I've set an alert in the jquery, but it doesn't enter the function in the controller to pull down the corresponding list for the second dropdown. Anyone know where I might be going wrong? , Could you please try :
code :
$("#FlightTime_AirlineID").change(function () {
        var id = $('select#FlightTime_AirlineID').val();
        populate(id);
    }).change();
jqGrid - All rows in inline edit mode and cascading dropdowns

jqGrid - All rows in inline edit mode and cascading dropdowns


By : Frank Averhoff
Date : March 29 2020, 07:55 AM
it should still fix some issue I have found a solution for my issue: 1. I have removed dataInit part - it seems to not working in my case. 2. On gridComplete I changing value for editoptions before setting row in edit mode and after that go back to set allsubgroups for editoptions.
code :
            gridComplete: function() {
                //loadComplete: function() {
                //set jqGrid datatype to local
                $($grid).setGridParam({ datatype: 'local' });

                //set all rows in editRow mode
                var $this = $(this), ids = $this.jqGrid('getDataIDs'), i, l = ids.length;
                for (i = 0; i < l; i++) {


                    var groupId = $this.jqGrid('getCell', ids[i], 'Group');
                    var cm = $this.jqGrid('getColProp', 'SubGroup');
                    cm.editoptions = { value: gridDataSubGroup[groupId]};
                    $this.jqGrid('editRow', ids[i],
                    {
                        keys: true,

                        oneditfunc: function() {
                        }
                    });
                    //asigne back all values for 
                    cm.editoptions = { value: gridDataSubGroupAll };

                };
            },
Display related columns from database in two cascading dropdowns

Display related columns from database in two cascading dropdowns


By : Vivek Raghav
Date : March 29 2020, 07:55 AM
jqgrid cascading dropdown lists in pop up edit mode

jqgrid cascading dropdown lists in pop up edit mode


By : abdul owoiya
Date : March 29 2020, 07:55 AM
around this issue The old answer shows how one can implement the dependent selects. You use form editing. Thus the editing field of PriceCode column inside of change event handler of CurrCd column.
Cascading dropdowns using MVC Razor Entity Framework and stored procedures

Cascading dropdowns using MVC Razor Entity Framework and stored procedures


By : hye ji
Date : March 29 2020, 07:55 AM
this one helps. Compared to thick client apps, web cascading drop down lists are convoluted and complex, but that's web programming! Keep in mind that javascript doesn't care about your MVC stuff at all. You just need a web method (something that responds to web URL) that takes a parameter and returns the correct list in the correct format. Whatever method it uses internally (EF stored procedure, hard coded list, PHP reading a text file) doesn't make any difference
To do what you want, you need to add an "event handler" to your drop down which calls some javascript which calls your method to look up the correct list, then populates the target drop down with that list.
code :
@Html.DropDownList("Manufacturer", 
                   ViewData["Manufacturer"] as SelectList, 
                   htmlAttributes: 
                         new { @class = "form-control" , 
                               @onchange = "refreshModelFromManufacturer()"
                             }
                   )
function refreshModelFromManufacturer()() {
    // get references to the source and target drop downs html controls
    // These are jquery searches to find the drop down controls

    // find a control with id=Manufacturer
    src = $("#Manufacturer");

    // find a control with id=Model (you need to add this to your view)
    tgt = $("#Model");

    // clear drop down
    tgt.empty();

    // Get new model dataset via ajax 
    // based on manufacturer
    // The url parameter points at your web method
    $.ajax({
        type: 'GET',
        url: 'Home/GetModels',
        dataType: 'json',
        data: { brandName: src.val() },
        // success is called when dataset returns
        success: function (p) {
                // Populate with each returned member
                $.each(p, function (i, pr) {
                    tgt.append(
                        '<option value="' + pr.Value + '">' +
                        pr.Text + '</option>'
                        );
                })
            }
        });
    }
public JsonResult GetModels(string brandName)
{
    var list = db.prcGetModels(brandName)

    return Json(new SelectList(list, "your id column","your label column"));
}
@Html.DropDownList("Customer_ID", null, htmlAttributes: new { @class = "form-
control", @onchange = "refreshProjectFromClient()" })
Related Posts Related Posts :
  • jQuery target next of the same class in the whole DOM
  • encoding must be a valid encoding error in process encoding
  • How to do a date range to view data from selected date highcharts
  • How do I refactor this composed function with Ramda.js?
  • jQuery to serialize selected option's value, not label
  • Convert object to Chartis.js structure
  • Dynamic import with not bundled file
  • Click handler not firing for elements rendered in Ajax Callback - only in Safari
  • Math.max.apply gives an error CreateListFromArrayLike called on non-object
  • get the parent nodes to a given node in d3 dendogram
  • is-dropdown-submenu-parent makes links unclickable on Opera and Chrome
  • JS: Sum column values and updating result on change
  • Query against nested object keys
  • Fullcalendar getting its parent colspan
  • How to retrieve a dynamic number of elements by id
  • How to access redux variables and functions from deep components
  • Efficiently access Array.prorotype.filter single-item returns
  • PHP var into Javascript
  • How to parse json with javascript/jquery if content matches string
  • How can I make a pyramid based on alphabet?
  • Javascript sorting a csv rows and displaying in table
  • How to get specific data from json from api using ajax. The json looks strange to me
  • react js html5 video not working
  • Javascript Angular 4 Change ngClass from another Component
  • Hide multiple table columns with javascript
  • Convert datetime to ISO Format using moment js
  • Dynamically adjust canvas size depending on content
  • setTimeout function with document on click
  • Need advice on nested Promises.all
  • Google Captcha expiration time
  • Syntax of Javascript TAPE unit test
  • Parse php json to javascript
  • Write to Internet Explorer javascript console with vba in excel
  • 2 Forms with Jquery
  • Why the loop stops right in the middle?
  • filter system for restaurant booking
  • how to add active class in framework nav menu when (add/edit) pages are opened
  • Port a js map in dart
  • How to get value from select using javascript
  • Audio won't be muted with JavaScript - removing audio tags with mutationobserver needed
  • How to include an HTML/Javascript game into reactJS website
  • Convert Nodejs server into node module
  • Strage Vue behaviour. V-if does not watch properly
  • Is it possible to use map/filter/reduce inside a promise by returning the result with Promise.resolve?
  • Does EcmaScript have any rule where whitespace is important for the compiler during parsing
  • How is DOM and Virtual DOM represented in memory?
  • cannot display text onchange select option
  • My gulpfile can edit (change) and delete file, but dont copy new (add) files
  • How do I reset scroll position of paper-dialog-scrollable?
  • Loading unlooped gif-animation several times
  • Strange error from Google API: initializeAutocomplete is not a function
  • Array state variable is not being set during componentWillMount
  • Stop refresh on form submit when using javascript
  • Npm WARN deprecated babel-preset-es2015@6.24.1: Thanks for using Babel: we recommend using babel-preset-env now: please
  • Cant get wheel scroll delta on Firefox
  • Puppeteer with Prompt, ignoring rest of function
  • VueJS Form Input Binding
  • How To Extend mail.Chatter Widget in Javascript Odoo 10
  • How Chk two checkboxes at a time using jQuery
  • Broken "if" statement in JavaScript code…
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org