0

I have dropdown list which was created dynamically like:

            @for(int i=0;i<=count;i++)
              {
                @Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { @class = "ddlProjectvalue" })
              }

             <input type="submit" value="Add Record" name="btn"/>

in Contoller I am loading data to dropdownlist:

            [HttpPost]
            Public ActionResult Timesheet()
            {
                 TimsheetModel model=new TimesheetModel();

              if(btn=="Add Record")
              {
                  var data= Session["ddlData"] as IEnumerable<SelectListItem>;
                  SelectList list1=new SelectList(data,"Value","Text",model.ProjID);
                  ViewBag.ProjectList=list1;
                  count++; // ADDS NEW RECORD
                  return View();
              }
              else
              {
                 var result = (from proj in db.PROJECTs where proj.IS_DELETED == "N" select new { Value = proj.ID, Text = proj.NAME })

            SelectList list = new SelectList(result, "Value", "Text", tm.PROJ_ID);

            ViewBag.ProjectList = list;//Data loaded here for Dropdown list
              }
            return View();
            }

Now My Scenario is if count=5 which means if we have five dropdown lists, when I select item in first dropdown list should not show in second dropdown list and if we have select item in second dropownlist should not show items of first and second in third dropdown list. for that I have written script like:

    <script>
    $(document).ready(function () {
        $('.ddlProjectvalue').change(function () {

            var id = $('.ddlProjectvalue').attr('id');
            var selector = "#" + id;
            var selectedValue = $(this).val();
            $.ajax({
                url: "@Url.Action("GetDDLData","Employer")",
                data: { selectedValue: selectedValue, id: id },
                dataType: "json",
                type: "GET",
                error: function () {
                    alert(" An error occurred.");
                },
                success: function (data) {
                    debugger;

                    $("" + selector + "").removeClass("ddlProjectvalue");
                    $('.ddlProjectvalue').empty();
                    var optionhtml1 = '<option value="' +
                     0 + '">' + "--Choose a Project--" + '</option>';
                    $(".ddlProjectvalue").append(optionhtml1);

                    $.each(data, function (i) {

                        var optionhtml = '<option value="' +
                    data[i].Value + '">' + data[i].Text + '</option>';
                        $(".ddlProjectvalue").append(optionhtml);
                    });
                }
            });
        });
    });

    </script>

and when i pass selected value to controller like:

   public ActionResult GetDDLData(string selectedValue, string id, string addrecord)
    {
        int projectid = Convert.ToInt32(selectedValue);
        if (id == "GetTimeSheetDetails_0__PROJ_ID")
        {
            IEnumerable<SelectListItem> projectslist = (from proj in db.PROJECTs where proj.IS_DELETED == "N" && proj.ID != projectid select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
            var result = new SelectList(projectslist, "Value", "Text", tm.PROJ_ID).ToList();
            Session["ddlData"] = result;
            ViewBag.ProjectList = result;
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        else
        {

            var result = Session["ddlData"] as IEnumerable<SelectListItem>;
            var query = (from data in result where data.Value != selectedValue select data) as IEnumerable<SelectListItem>;
            Session["ddlData"] = query;
            return Json(result, JsonRequestBehavior.AllowGet);
        }

    }

Now my problem is when I add new record by clciking on Add button, loading Session["ddldata"] data to total dropdown list instead it should remain selectlist item in first dropdownlist for first time, I need like when i first select a dropdownlist item in first dropdown list it should remain same when add record also. it means i should prevent server side load on first select list item and vice versa.

Note: Due to some issues i should add record on server side only How I can prevent it, I tried like preventDefault or return false using jquery, but not working, Any Ideas? how can I fix it.

1 Answer 1

0

I think you are overcomplicating things here. You don't really need to request new options from server. Why not just filter the option out on the javascript side?

$(document).ready(function() {
    $('.ddlProjectvalue').change(function() {
        updateDDLValues();       
    });
    updateDDLValues();
});

function updateDDLValues() {
    // Display all
    $('.ddlProjectvalue option').show();
    // Hide all selected options from other selectlists
    $('.ddlProjectvalue').each(function(i,element) {
        var selectedvalue = $(element).find('option:selected').val();
        $('.ddlProjectvalue').not(element).find('option[value="'+selectedvalue+'"]').hide();
    });    
}

Fiddle:

http://jsfiddle.net/Pt7qV/2/

Update:

As for the serverside part of your question, there are some serious flaws in your code. You increase the count property in your controller and use the variable clientside. First you'd think that's how it's done but nope it doesn't work that way.

You are returning View when Add Record is submitted but you aren't returning any model with it.

Your TimsheetModel would look something like this:

public class TimsheetModel
{
    public int Count {get; set;}
}

In your controller you pass this to the view:

 TimsheetModel model=new TimesheetModel();
 if(btn=="Add Record")
 {
      var data= Session["ddlData"] as IEnumerable<SelectListItem>;
      SelectList list1=new SelectList(data,"Value","Text",model.ProjID);
      ViewBag.ProjectList=list1;
      model.Count++; // ADDS NEW RECORD
      return View(model);
 }

And in your view:

@model TimsheetModel

@for(int i=0;i<=Model.Count;i++)
{
      @Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { @class = "ddlProjectvalue" })

}

<input type="submit" value="Add Record" name="btn"/>

I'd suggest you to go back to tutorials or books a bit, this is quite basic stuff after all. I won't go into how you are going to handle database side etc. since I think this answer would just escalate into explaining basic stuff.

Sign up to request clarification or add additional context in comments.

8 Comments

Ya, this process getting for me, but when i add record again it should filter except first selected item, when i add record count in increasing on server side, there i am loading data, that's the problem @sormii
And I loading data from database dynamically.
NO Dude, According to your answer, first selected value in dropdown list it is not retain same select value, as because we are loading data to drop downlist again, i think solution is if we load data to it should not load again , it should be remain with same selected value, That's the problem @sormii
Can we keep always same selected value, even though we load data to it, is there any chances like that
Yes, you must post the selected values of the selectlists. Selectlist has selected property which you will need to keep track of the previously selected values. Take a look at this stackoverflow.com/questions/17555241/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.