C# DropDownList postback - c#

I am using MVC ASP to create a series of dropdownlist's that are populated by SQL stored procedures. However, each successive dropdownlist needs to be populated by passing the selection of the previous list as a parameter to the procedure call. How can I POST the selection of the list created using:
#Html.DropDownListFor(x => x.environmentName, new SelectList(Model.environmentName))
?
I was attempting to save it to a modelView and then pass the view to the controller again, but I feel this is a poor way to go about it.

Here is a JQuery solution I wrote for 3 cascading drop-downs with ajax callbacks to the controller to fill the next list based on the previous choices. This might get you going in the right direction.
Select: <select id="category" style="width: 150px">
<option></option>
#foreach (string cat in ViewBag.Categories)
{
<option>#cat</option>
}
</select><span id="errorforcategory" style="color: red"></span>
<select id="subcategory1" disabled="disabled" style="width: 150px"><option></option> </select>
<select id="subcategory2" disabled="disabled" style="width: 150px"><option></option></select>
<script type="text/javascript">
$("#category").change(function () {
$("#subcategory1").load('#Url.Action("GetSubCategory")' + "?category=" + $("#category").val());
$('#subcategory2').empty();
$('#subcategory2').append($("<option></option>"));
$('#subcategory2').attr('disabled', 'disabled');
}).ajaxStop(function () {
if ($('#subcategory1 option').size() > 2) {
$('#subcategory1').attr('disabled', '');
} else {
$('#subcategory1').attr('disabled', 'disabled');
}
});
$("#subcategory1").change(function() {
if ($("#subcategory1").val().trim()) {
$("#subcategory2").load('#Url.Action("GetSubCategory")' + "?category=" + $("#category").val() + "&subcategory=" + $("#subcategory1").val());
} else {
$('#subcategory2').empty();
$('#subcategory2').attr('disabled', 'disabled');
}
}).ajaxStop(function() {
if ($('#subcategory2 option').size() > 2) {
$('#subcategory2').attr('disabled', '');
} else {
$('#subcategory2').attr('disabled', 'disabled');
}
});
And then in your controller you can call your Stored Proc using whatever method you like then build out your result option text.
public string GetSubCategory(string category, string subcategory)
{
string returnval = "<option></option>";
if (!string.IsNullOrEmpty(subcategory))
{
foreach (
var cat in
db.Categories.Where(c => c.category1 == category && c.subcategory1 == subcategory)
.Select(c => c.subcategory2)
.Distinct())
{
if (!string.IsNullOrEmpty(cat.Trim()))
returnval += "<option>" + cat + "</option>";
}
return returnval;
}
return Enumerable.Aggregate(db.Categories.Where(c => c.category1 == category).Select(c => c.subcategory1).Distinct().Where(cat => !string.IsNullOrEmpty(cat.Trim())), returnval, (current, cat) => current + ("<option>" + cat + "</option>"));
}

Related

Displaying multivalued attributes from model in columns

I am just kicking things off with Kendo UI, I could not find a way to display multivalued attributes in a column, with respect to a value in the preceeding column. Here is the representational mockup of the view that I want:
The values in column 2 and 3 belong to the Value 1, 2 and 3 respectively. I have the model, which is a list containing another list for columns 2 and 3. Here is what I have so far:
#model List<Customer>
<div class="left" style="margin-top: 30px; margin-left: 0px;">
<div style="margin-bottom: 5px;">
<span style="font-weight: bold">Customer Data</span></div>
#(Html.Kendo().Grid<Customer>()
.Name("gvCustomerData")
.Columns(columns =>
{
columns.Bound(Model => Model.CustomerName);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax().Model(model => model.Id(Model => Model.CustomerId))
.Read(read => read.Action("GetCustomerData", "Customer", new { DeptId= #ViewBag.DeptId})))
)
</div>
In this case, the values could be the customers phone numbers or projects that he is working on. I do not want to manually iterate over the Model List and construct the raw HTML against that. Can Kendo help to simplify the process?
While Kendo UI does support merged column headers, it doesn't seem to support your requirement.
However, I found this piece of code, perhaps it helps you:
function mergeGridRows(gridId, colTitle) {
$('#' + gridId + '>.k-grid-content>table').each(function (index, item) {
var dimension_col = 1;
// First, scan first row of headers for the "Dimensions" column.
$('#' + gridId + '>.k-grid-header>.k-grid-header-wrap>table').find('th').each(function () {
if ($(this).text() == colTitle) {
// first_instance holds the first instance of identical td
var first_instance = null;
$(item).find('tr').each(function () {
// find the td of the correct column (determined by the colTitle)
var dimension_td = $(this).find('td:nth-child(' + dimension_col + ')');
if (first_instance == null) {
first_instance = dimension_td;
} else if (dimension_td.text() == first_instance.text()) {
// if current td is identical to the previous
// then remove the current td
dimension_td.remove();
// increment the rowspan attribute of the first instance
first_instance.attr('rowspan', typeof first_instance.attr('rowspan') == "undefined" ? 2 : first_instance.attr('rowspan') + 1);
} else {
// this cell is different from the last
first_instance = dimension_td;
}
});
return;
}
dimension_col++;
});
});
}

How to handle repeating form fields in ASP MVC

I have a form which asks users for their personal info and their family members.
fields of the family members section is repeating.
my question is what is best practice to handle these kind of repeating forms?
I currently use AJAX to repeat forms but how to collect data from these repeating fields?
since some one asked for how I repeat form, I do it like this:
AJAX Call
$(document).on('click', '.btn-add-item', function (e) {
e.preventDefault();
var $results = $('#results');
$.ajax({
url: '/AJAX/AddFamilyForm',
type: 'post',
success: function (data) {
$(data).appendTo($results);
afterAJAX();
}
});
});
C# code
[HttpPost]
public PartialViewResult AddFamilyForm()
{
if (!Request.IsAjaxRequest()) return null;
return PartialView("_FamilyForm");
}
This is some skeleton code on how to get this to work with proper model-binding in MVC. You'll need to write some JS to be able to delete/add new rows.
Model
public class MyModel
{
public FamilyMembers[] FamilyMembers { get; set; }
}
View
<button id="addNewFamilyMember" type="button">Add</button>
#if (Model.FamilyMembers != null)
{
for (int i = 0; i < Model.FamilyMembers.Length; i++)
{
<tr>
<td>
<button type="button">Delete</button>
#Html.Hidden("FamilyMembers.Index", i)
</td>
<td>
#Html.TextBoxFor(m => Model.FamilyMembers[i].Relation)
</td>
<td>
#Html.TextBoxFor(m => Model.FamilyMembers[i].FullName)
</td>
</tr>
}
}
Below is the code for adding a new member. It creates html dynamically and is able to bind to the posted model because of naming conventions. time gives each added row a unique id so all the data stays together.
JS (using Jquery)
var hidden = '#Html.Hidden("FamilyMembers.Index", "{id}")';
var relationHtml = '#Html.TextBox("FamilyMembers[{id}].Relation")';
var fullNameHtml = '#Html.TextBox("FamilyMembers[{id}].FullName")';
$("#addNewFamilyMember").on("click", function () {
var time = Date.now();
var deleteHtml = "<button type='button'>Delete</button>";
$("#familyMembers-table").find("tbody")
.append($("<tr><td>" + hidden.replace("{id}", time) + deleteHtml + "</td>" +
"<td>" + relationHtml.replace("{id}", time) + "</td>" +
"<td>" + fullNameHtml.replace("{id}", time) + "</td></tr>"));
});
One of the solution could be combination of hidden field and control name.
Steps:
Use a hidden field to keep the count the number of row.
Create controls with name like text_relation_1 for first row and text_relation_2 for second row and so on
Generate other controls in same way.
Increase and decrease the hidden field value so that when values post you can know the number of rows added by the user
On your action use FormCollection and loop though hidden field number and get the values from FormCollection
Like suppose I created 3 rows then I can create a action like below
public ActionResult SomeActionMethod(FormCollection formCollection, string hid)
{
for(int i=1;i<hid;i++)
{
var relationId="text_relation_"+i;
var firstrealtion=formCollection[relationId];
...
}
}
You don't need any extra Ajax requests for this, since you can use established and standard <form> features.
Just append [] to the name of the added forms and you'll end up with an array rather than a single value in your HTTP request once the form is submitted:
<input type="text" name="relation[]" /><input type="text" name="fullname[]" />
<input type="text" name="relation[]" /><input type="text" name="fullname[]" />
<input type="text" name="relation[]" /><input type="text" name="fullname[]" />
In this example you'd end up with an array relation and an array fullname, both containing your datasets.

how to Prevent Serverside data load to dropdown list in Asp.net MVC

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.
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.

MVC Cascading Drop Down Not Selected When Editing

I am developing an MVC 4 web application. One of the Razor views has two drop down lists. The first drop down list is populated by the ViewModel data which is passed to the view. The secondary drop down list is populated using a JQuery and Ajax call based on the selected ID from the first drop down list (cascading).
I have this working fine, however, whenever a user wishes to edit an existing record I can't get the selected secondary drop down list value to be selected.
This is my Razor code for the two drop down lists
<div class="lbl_a">
Employer:
</div>
<div class="editor-field sepH_b">
#Html.DropDownListFor(model => model.Employer, Model.EmployerList, "Select", new { #class = "inpt_a" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DirectorateID, "Directorate/ Service Group")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.DirectorateID, Model.DirectorateList, "Select")
</div>
This is my JQuery code
$(document).ready(function () {
//Pre load on page load
onEmployerChange();
//Hide and show DIVS based on selection
$("#Employer").change(onEmployerChange);
function onEmployerChange() {
var dataPost = { orgID: val };
$.ajax({
type: "POST",
url: '/User/GetDirectorates/',
data: dataPost,
dataType: "json",
error: function () {
alert("An error occurred." + val);
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#DirectorateID").html(items);
}
});
}
}
});
When a user selects a value from the first drop down list, the selected ID is passed to the GetDirectorates action within the User Controller.
This is my GetDirectorates action which returns Json data
public ActionResult GetDirectorates(string orgID)
{
if (String.IsNullOrWhiteSpace(orgID))
orgID = "0";
var Directorates = _ListService.GetListItemsByOrganisationID(Convert.ToInt32(orgID));
List<SelectListItem> directorateList = new List<SelectListItem>();
directorateList.Add(new SelectListItem() { Text = "Select", Value = "" });
foreach (var directorate in Directorates)
{
directorateList.Add(new SelectListItem() { Text = directorate.description, Value = directorate.listItemID.ToString(), Selected = false });
}
return Json(new SelectList(directorateList, "Value", "Text"));
}
Whenever the users wishes to edit an existing record I pass both the values for the first and second drop down list. Both drop down lists are populated with the proper data as expected, however, the selected value for the second drop down list is never selected.
This is a shortened version of the Edit action which the user calls when attempting to edit an existing record but shows the two drop down list selected values being passed.
public ActionResult EditNonMember(int id, string feedback, string courseDateID, string courseID)
{
//code to retrieve data here
vm.Employer = UserDetails.Employer;
vm.DirectorateID = UserDetails.DirectorateID;
return View(vm);
}
Would anyone be able to help me with this?
Thanks.
You need to get the directorate list for the saved employer id and set the DirectorateList collection and then the DirectorateID (from saved record);
public ActionResult EditNonMember(int id, string feedback, string courseDateID,
string courseID)
{
//code to retrieve data here
var userDetails=repositary.GetUserFromSomeId(id);
vm.Employers=GetEmployers();
vm.Employer = userDetails.Employer;
vm.DirectorateList=GetDirectorateListForEmployer(userDetails.Employer);
vm.DirectorateID = userDetails.DirectorateID;
return View(vm);
}
private List<SelectListItem> GetEmployers()
{
// to do : Return all employers here in List<SelectListItem>
}
private List<SelectListItem> GetDirectorateListForEmployer(int employerId)
{
// to do : Return all Directorates for the selected employer
}
This should do the trick:
var subSelect = $("#DirectorateID");
// clear the selection
subSelect.empty();
//append each option to the list
$.each(data, function (i, item) {
subSelect.append($('<option/>', {
value: item.Value,
text: item.Text
}));
});
Rather than setting it via the html method, I'm simply appending an option.
This is the method I use for cascading dropdown lists using ajax.

3 Dropdown List cascade using MVC3 & LinqSql

I have 3 dropdownlist i wanna make 3 dropdownlist with cascade. I am using LinqSql for database..
I have 3 tables Product(id,name), Design(id,master_id,name), Model(id,design_id,name)
master_id bound to Product(id), design_id bound to Design(id)..
I want to create one dropdown which is gonna show Products and than when i choose a product its gonna make Design dropdown enabled else it will stay disabled.. also here is the tricky part that i couldnt solve and i need great explanation in here creating 3rd dropdown which is gonna be disabled normally till a Design is chosen.
Each of them gonna populate a lower dropdownlist bound to them.Its like;
Product gonna enable and populate Design,
Design gonna enable and populate Model.
I can do it with 2 dropdowns but when it comes to 3 dropdown i stuck really badly im on (brain-freeze)..
I already checked the other questions couldnt find any solution for my self. As i said im using LinqSql i need a solution about 3 cascadingdropdown list for this type of data reach.
thanks already for anything u can do! and if u can explain Model-View-Controller partials and the parameters and why you use them that would be awesome. Iam kinda beginner at this MVC3.
I would approach the problem something like this:
First, in the controller, we'll set up have the following methods:
public JsonResult GetDesignsForProduct(int productId)
{
// Instantiate our context and do whatever goo we need to select the objects we want
using (MyDatabaseContext ctx = new MyDatabaseContext())
{
return Json(ctx.Designs.Where(d => d.master_id == productId).ToList(), JsonRequestBehavior.AllowGet);
}
}
public JsonResult GetModelsForDesign(int designId)
{
// Instantiate our context and do whatever goo we need to select the objects we want
using (MyDatabaseContext ctx = new MyDatabaseContext())
{
return Json(ctx.Models.Where(d => d.design_id == designId).ToList(), JsonRequestBehavior.AllowGet);
}
}
I've turned on "get" here; if your data contains sensitive information - user names/e-mail addresses, other proprietary or legally protected data, etc. - you can change this to only allow "post", and modify your Javascript accordingly. See Phil Haack's article.
Also, if you expect this data to change frequently, these methods will cache it by default according to your application's cache settings. You can add an OutputCache attribute on the method to alter this behavior.
Then, in the view you'll have some AJAX plumbing, something like this:
function LoadDesigns() {
// Get the currently-selected value in our Product dropdown
var prod = $("#Product").val();
// Call our controller method and process the list of Design objects
$.getJSON('#Url.Content("~/ControllerName/GetDesignsForProduct")', { productId: prod },
function (designs) {
$("#Design").empty();
$.each(designs, function (i, c) {
$("#Design").append(
$('<option></option>').val(c.id).html(c.name)
);
});
});
}
function LoadModels() {
// Get the currently-selected value in our Design dropdown
var des = $("#Design").val();
// Call our controller method and process the list of Model objects
$.getJSON('#Url.Content("~/ControllerName/GetModelsForDesign")', { designId: des },
function (models) {
$("#Model").empty();
$.each(models, function (i, c) {
$("#Model").append(
$('<option></option>').val(c.id).html(c.name)
);
});
});
}
Finally, define all three drop-downs as follows:
#Html.DropDownList("Product", productSelectList, new { onchange = "LoadDesigns()" })
#Html.DropDownList("Design", null, new { onchange = "LoadModels()" })
#Html.DropDownList("Model")
Don't forget that the HTML helpers are really just shortcuts to generate the underlying HTML, and in Razor you frequently just go straight to HTML instead of messing with the helpers. So you could just as easily write these as:
<select id="Product" onchange="LoadDesigns()">
#foreach (var prod in products) {
<option value="#prod.id">#prod.name</option>
}
</select>
<select id="Design" onchange="LoadModels()"></select>
<select id="Model"></select>
Forget to set my finished work.. People may wanna see how it happens..
Here is my:
View + Jquery
$(function () {
$("select#Design").attr('disabled', 'true');
$("select#Model").attr('disabled', 'true');
$("select#Product").click(function () {
var prod = $("select#Product option:selected").val();
if (prod == "" || prod == 0) {
$("select#Design").attr('disabled', 'true');
$("select#Model").attr('disabled', 'true');
} else {
$.getJSON('#Url.Content("~/Admin/GetDesigns/")', { productId: prod }, function (data) {
$("select#Design").empty();
$("select#Model").empty();
$.each(data, function (i, c) {
$('select#Design').append('<option value="' + c.Value + '">' + c.Text + '</option>');
})
$("select#Design").removeAttr('disabled');
$("select#Design option:first").attr('selected', 'selected');
var des = $("select#Design option:selected").val();
if (des == "" || des == 0) {
$("select#Model").attr('disabled', 'true');
} else {
$.getJSON('#Url.Content("~/Admin/GetModels/")', { designId: des }, function (data) {
$("select#Model").empty();
$.each(data, function (i, c) {
$('select#Model').append('<option value="' + c.Value + '">' + c.Text + '</option>');
})
$("select#Model").removeAttr('disabled');
$("select#Model option:first").attr('selected', 'selected');
})
}
})
}
})
})
reason i use Jquery this way to fill all dropdowns and select first elements as default selection! When i choose an element from first dropdown the other two dropdowns starts to fill themselves and select their first element as default selection.. same code can be used for other dropdowns click function just like this:
$("select#Design").click(function () {
var des = $("select#Design option:selected").val();
if (des == "" || des == 0) {
$("select#Model").attr('disabled', 'true');
} else {
$.getJSON('#Url.Content("~/Admin/GetModels/")', { designId: des }, function (data) {
$("select#Model").empty();
$.each(data, function (i, c) {
$('select#Model').append('<option value="' + c.Value + '">' + c.Text + '</option>');
})
$("select#Model").removeAttr('disabled');
$("select#Model option:first").attr('selected', 'selected');
})
}
});
View
#using (Html.BeginForm("Index", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td style="background-color:#e8eef4;" rowspan="3">
</td>
<td style="width:190px; background-color:#e8eef4;">
#Html.DropDownList("Product", (SelectList)ViewData["ProductList"], "Please Select Product", new { style = "width:190px; padding:4px; margin:4px;" })
</td>
<td rowspan="3" style="width:400;">
</td>
<td style="background-color:#e8eef4;">
</td>
<td style="background-color:#e8eef4;" rowspan="3">
</td>
</tr>
<tr>
<td style="background-color:#e8eef4;">
<select id="Design" style="width:190px; padding:4px; margin:4px;">
<option label="Please Select Design" selected="selected"></option>
</select>
</td>
<td style="background-color:#e8eef4;">
</td>
</tr>
<tr>
<td style="background-color:#e8eef4;">
<select id="Model" style=" width:190px; padding:4px; margin:4px;">
<option label="Please Select Model"></option>
</select>
</td>
<td style="background-color:#e8eef4;">
</td>
</tr>
</table>
}
Just cause im using linqtosql and im too lazy to make a repository..
This is my CONTROLLER
public class AdminController : Controller
{
public linqVipDataContext db = new linqVipDataContext();
//
// GET: /Admin/
public ActionResult Index()
{
IEnumerable<SelectListItem> ProductItems = db.Products.AsEnumerable().Select(c => new SelectListItem()
{
Text = c.name,
Value = c.id.ToString(),
Selected = true,
});
SelectList prod = new SelectList(ProductItems, "Value", "Text");
ViewBag.ProductList = prod;
return View();
}
//
//Fill the Design List..
public JsonResult GetDesigns(int productId)
{
/*var data = dbs.Designs.Where(d => d.master_id == productId).ToList();*/
IEnumerable<SelectListItem> DesignItems = db.Designs.Where(c => c.master_id == productId).AsEnumerable().Select(c => new SelectListItem()
{
Text = c.name,
Value = c.id.ToString()
});
SelectList des = new SelectList(DesignItems, "Value", "Text");
return Json(des, JsonRequestBehavior.AllowGet);
}
//
//Fill the Model List..
public JsonResult GetModels(int designId)
{
/*This code down here! Doesnt work and says it's type is unknown*/
/*var data = dbs.Models.Where(d => d.design_id == designId).ToList();*/
/*For that reason im using this code*/
IEnumerable<SelectListItem> ModelItems = db.Models.Where(d => d.design_id == designId).AsEnumerable().Select(c => new SelectListItem()
{
Text = c.name,
Value = c.id.ToString()
});
SelectList mods= new SelectList(ModelItems, "Value", "Text");
return Json(mods, JsonRequestBehavior.AllowGet);
}
Json requires Value and Text 2 param seperated for creating a selectlist option.. So i must return my value that way..
I posted this cause i found some breakdowns at ur code, ty again for showing me this solution it gave me the idea and allowed me to solve all problems so this is the fully working code.. Ty again. Hope its usefull.

Categories

Resources