Jquery dynamic load dropdownlist - ajax

I have a problem about dynamic load dropdownlist. I debuged my ashx, it do post the data. But dropdownlist have no value.
Here is my Aspx page
<script type="text/javascript">
$(function() {
$.post("ContentLoad.ashx", function(datas) {
for(var i = 0; i < datas.length; i++) {
var data = datas[i];
var option = $("<option value='"+data.Id + "'>" +data.Title + "</option");
$("#ddlClassId").append(option);
}
},"json");
});
</script>
In the html have a dropdownlist.
<asp:DropDownList ID="ddlClassId" runat="server" AutoPostBack="True">
</asp:DropDownList>
And here is my ashx code:
public class ContentLoad : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
BLL.ChannelManeger bll = new BLL.ChannelManeger();
DataTable dt = bll.GetList(0, 0);
Data[] datas = new Data[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
string id = dr["Id"].ToString();
int ClassLayer = int.Parse(dr["ClassLayer"].ToString());
string title = dr["Title"].ToString().Trim();
if (ClassLayer == 1)
{
datas[i++] = new Data() { Id = Convert.ToInt32(id), Title = title };
}
else
{
title = "├ " + title;
title = StringOfChar(ClassLayer - 1, " ") + title;
datas[i++] = new Data() { Id = Convert.ToInt32(id), Title = title };
}
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
context.Response.Write(serializer.Serialize(datas));
}
public static string StringOfChar(int strLong, string str)
{
string ReturnStr = "";
for (int i = 0; i < strLong; i++)
{
ReturnStr += str;
}
return ReturnStr;
}
public bool IsReusable
{
get
{
return false;
}
}
}
class Data
{
public int Id { get; set; }
public string Title { get; set; }
}

In your code there was a typo inside for loop and also since dropdown list is a server control, its id might change so you should not use id selector unless you use ClientID of the control. I have simplied your code using $.each loop take a look.
$(function() {
$.post("ContentLoad.ashx", function(datas) {
var $ddl = $("select[id*=ddlClassId]");
$.each(datas, function(){
$ddl.append("<option value='"+this.Id + "'>" +this.Title + "</option");
});
},"json");
});

look at this line: var data = data[i];
it should be var data = datas[i];

Related

Call MVC4 partial view with Jquery Ajax

I need you help with my mvc4 project. I have 2 drop down menus. When i select firs one, the second is automatically populated with help of Jquery and Ajax. When i select the other one, which is now populated with some data, i need to invoke a method which calls a PL/SQL procedure, and i need to pass a value to that method, which is selected in a second drop down menu.
That method returs some data which I need to pass to my partial view and in that partial view i need to generate a tree view from passed data.
So far i was able to generate TreeView (using jsTree) in my partial view when i hardcoded a value and invoked my method from controler, but i need to do that when i select a value from my second drop down list.
This is my code:
My Controller
public class IndexController : Controller
{
public ActionResult Index()
{
EpfeSelectScreen model = new EpfeSelectScreen();
#region Country
var b = (from a in dbEntitiesErste.CONFIG_COUNTRIES
orderby a.COUNTRY_ID
select new Countries
{
Text = a.COUNTRY_NAME,
Value = a.COUNTRY_ID
});
model.Country = b.OrderBy(x => x.Text).ToList();
#endregion
#region Oracle Stored Procedures
List<TreeNode> list = new List<TreeNode>();
list = ClassData.GetAllClasses(1); //hardcoded value 1 Here goes the value from second drop down list
var TopHierarchy = list.Where(x => x.ParentId == -1).FirstOrDefault();
SetChildren(TopHierarchy, list);
#endregion
var pmViewModel = new MainViewModel
{
FullModelObject = model,
PartialModelObject = TopHierarchy
};
return View(pmViewModel);
}
#region generate Tree
private void SetChildren(TreeNode model, List<TreeNode> list)
{
var childs = list.Where(x => x.ParentId == model.ChildId).ToList();
if (childs.Count > 0)
{
foreach (var child in childs)
{
SetChildren(child, list);
model.Children.Add(child);
}
}
}
#endregion
#region jquery methods
[OutputCache(Duration = 0)]
[HttpGet]
public JsonResult Application(string[] Country)
{
var apl = new List<Applications>();
if (Country[0] == "")
{
//*aplications
var result = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
select new Applications
{
Text = a.APPLICATION_NAME,
Value = a.APPLICATION_ID
});//*.OrderBy(x => x.Text).ToList()
apl.Add(new Applications { Value = 0, Text = "--Please choose application--" });
apl.AddRange(result.OrderBy(x => x.Text).ToList());
}
else
{
var result = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
where Country.Contains(a.COUNTRY_ID)
select new Applications
{
Text = a.APPLICATION_NAME,
Value = a.APPLICATION_ID
}); //*.OrderBy(x => x.Text).ToList();
apl.Add(new Applications { Value = 0, Text = "--Please choose application--" });
apl.AddRange(result.OrderBy(x => x.Text).ToList());
}
var retVal = new { Application = aplikacije };
return Json(retVal, JsonRequestBehavior.AllowGet);
}
//[OutputCache(Duration = 0)]
//[HttpGet]
//public JsonResult Tree(int idApp)
//{
// var ret = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
// select new Applications
// {
// Text = a.APPLICATION_NAME,
// Value = a.APPLICATION_ID
// }).OrderBy(x => x.Text).ToList();
// return Json(ret, JsonRequestBehavior.AllowGet);
//}
#endregion
}
this is my main View (Index.cshtml)
#model EPFE.Models.ViewModels.MainViewModel
<!DOCTYPE html>
#{
ViewBag.Title = "EB";
}
<head>
<title>EBB</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script src="#Url.Content("~/Scripts/jquery-ui-1.10.3.js")" type="text/javascript"></script>
<script src="~/Scripts/Selections.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="#Url.Content("~/Scripts/jstree.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/Selection.css")" rel="stylesheet" type="text/css" />
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="#Url.Content("~/Content/themes/style.css")" rel="stylesheet" />
<script type="text/javascript">
var pathAplications = '#Url.Action("Application", "Index")';
var pathTreeView = '#Url.Action("Tree", "Index")';
</script>
</head>
<body>
<table>
<tr>
<td>
#Html.DropDownList("Country", new SelectList(Model.FullModelObject.Country, "Value", "Text"), "--Please select Country--")
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Application", new SelectList(Model.FullModelObject.Application, "Value", "Text"), "--Please choose application--")
</td>
</tr>
</table>
<fieldset class="Tree">
<div id="divtree">
<ul id="tree">
<li>
#Model.PartialModelObject.ObjectIdentifier
#Html.Partial("_TreeView", Model.PartialModelObject)
</li>
</ul>
</div>
</fieldset>
</body>
This is my partial view (_TreeView.cshtml)
#model EPFE.TreeViewModel.TreeNode
#foreach (var item in Model.Children)
{
<ul>
#if (item != null)
{
<li>
#item.ObjectIdentifier
#if (item.Children.Count > 0)
{
#Html.Partial("_TreeView", item)
}
</li>
}
</ul>
}
and these are my models
public class EpfeSelectScreen
{
public string Search { get; set; }
public string selectedApplication { get; set; }
public string selectedCountry { get; set; }
public string selectedMetaData { get; set; }
public string selectedTreeView { get; set; }
public List<Countries> Country { get; set; }
public List<Applications> Application { get; set; }
public List<SelectListItem> MetaData { get; set; }
public List<SelectListItem> References { get; set; }
public List<SelectListItem> ReferencedBy { get; set; }
public List<SelectListItem> TreeView { get; set; }
public EpfeSelectScreen()
{
Country = new List<Countries>();
Application = new List<Applications>();
References = new List<SelectListItem>();
ReferencedBy = new List<SelectListItem>();
TreeView = new List<SelectListItem>();
MetaData = new List<SelectListItem>();
}
}
Second one
public class MainViewModel
{
public EpfeSelectScreen FullModelObject { get; set; }
public TreeNode PartialModelObject { get; set; }
public MainViewModel()
{
FullModelObject = new EpfeSelectScreen();
PartialModelObject = new TreeNode();
}
}
and the last one
public class TreeNode
{
public int ParentId { get; set; }
public int ChildId { get; set; }
public int ObjectRelId { get; set; }
public string ObjectIdentifier { get; set; }
public string ObjectTypeId { get; set; }
public IList<TreeNode> Children { get; set; }
public TreeNode()
{
Children = new List<TreeNode>();
}
}
and these are my scripst
$(document).ready(function () {
$("#Country").on('change', CountryChange);
//$("#selectedApplication").on('change', ApplicationChange);
//*
$("#Application").on('change', ApplicationChange);
});
function CountryChange() {
var CountryIds = [];
$("#Country option:selected").each(function (i, selected) {
CountryIds[i] = $(selected).val();
});
$.ajax({
url: pathAplications,
type: 'GET',
data: { Country: CountryIds },
success: function (data) {
var apl = $("#Application");
apl.empty();
for (var j = 0; j < data.Application.length; j++) {
var item = data.Application[j];
var option = "<option value='" + item.Value + "'>" + item.Text + "</option>";
apl.append(option);
}
},
error: function (x, y) {
$("#displayError").html(x.val());
},
traditional: true
});
}
function ApplicationChange() {
var applicationId = [];
$("#Application option:selected").each(function (i, selected) {
applicationId[i] = $(selected).val();
});
$.ajax({
url: pathTreeView,
type: 'GET',
data: { Application: applicationId },
success: function (data) {
var tree = $("#selectedApplication");
trees.empty();
for (var j = 0; j < data.Application.length; j++) {
var item = data.Application[j];
var option = "<option value='" + item.Value + "'>" + item.Text + "</option>";
trees.append(option);
}
},
error: function (x, y) {
$("#displayError").html(x.val());
},
traditional: true
});
}
The function ApplicationChange catches the right value but i don't know how to use it to invoke my method for pl/sql procedure and return that data to partial view.
give your url like this
'#Url.Action("actionname","controllerNmae")',
also make sure if you are making a get or post request then the target action should have that attribute as well.
also you data type will be json for this.
or even better use like this
$.getJSON('#Url.Action("Controller Name here")',
function ()
{
});

how to use jstree ondemand with mvc3 razor

I have to display a treeview .But it will take much time, that's why I want to load this treeview on demand.At the first I want just display first level, and repeating that level by level.
This is the view
$("#onflycheckboxes").jstree({
json_data: {
"ajax": {
"url": function (node) {
var nodeId = "";
var url = ""
if (node == -1) {
url = "/TreeView/GetCollectionWS/source";
}
else {
nodeId = node.attr('id');
url = "/TreeView/GetCollectionWS/" + nodeId;
}
return url;
},
"type": "POST",
"dataType": "json",
"contentType": "application/json charset=utf-8"
}
},
checkbox: {
real_checkboxes: true,
checked_parent_open: true
},
plugins: ["themes", "json_data", "ui", "checkbox"]
});
this is the controller
public virtual ActionResult GetCollectionWS(string root)
{
int? nodeId = (root == source) ? (int?)null : Convert.ToInt32(root);
Object[] liste = new Object[100];
liste = DSClient.Views.Traitement.getTop(nodeId);
List<TreeViewNode> nodes = new List<TreeViewNode>();
for (int i = 0; (i < liste.Length && liste.ElementAt(i) != null);i++ )
{
bool leaf = false;
nodes.Add(new TreeViewNode()
{
id = Convert.ToString(DSClient.Views.Traitement.GetNodeId(liste.ElementAt(i))),
text = liste.ElementAt(i).Handle,
classes = leaf ? "file" : "folder",
hasChildren = !leaf
});
}
return Json(nodes);
}
when I try a breakpoint on the line return Json(nodes); I remarque that nodes contains
at the first {id=0,text=Collection-10,classes=folder,haChildren=false}
the view display nothing.Please, can any one help me??
public virtual string GetCollectionWS(string id)
{
Object[] liste = new Object[100];
client = new DSServiceClient();
if (id == "source")
{
Collection[] _top = new Collection[100];
client.Open();
_top = client.GetTopCollections();
client.Close();
for (int i = 0; i < _top.Length; i++)
{
DSClient.Controllers.Object obji = new DSClient.Controllers.Object();
obji.Handle = _top[i].Handle;
obji.Name = _top[i].Title;
liste[i] = obji;
}
}
else
{
client = new DSServiceClient();
client.Open();
Tree tree = client.GetTreeView(id);
client.Close();
liste = tree.listObjects;
}
var recursiveObjects = FillRecursive(liste);
string myjsonmodel = new JavaScriptSerializer().Serialize(recursiveObjects);
return myjsonmodel;
}
private static List<RecursiveObject> FillRecursive(Object[] flatObjects)
{
List<RecursiveObject> recursiveObjects = new List<RecursiveObject>();
for (int i = 0; (i < flatObjects.Length && flatObjects.ElementAt(i) != null); i++)
{
recursiveObjects.Add(new RecursiveObject()
{
data = flatObjects.ElementAt(i).Name,
id = flatObjects.ElementAt(i).Handle,
attr = new FlatTreeAttribute { id = flatObjects.ElementAt(i).Handle, selected = false },
children = null,
state = "closed"
});
}
return recursiveObjects;
}
Now I want to send the text and Id of nodes selected to my controller.
<script type="text/javascript">
var divId = [];
var divText = [];
$('#idjstree').value=function GetIDs() {
divId = [];
divText = [];
$("#onflycheckboxes").jstree("get_checked", null, true).each
(function () {
divId.push(this.id);
divText.push($(this).children('a').text());
});
return (divId);
}</script
and this is in the view
#:<div id="onflycheckboxes"></div>
#:<input type="hidden" id="idjstree" name="idjstree" value="" />
but always I get idjstree="" when I do a breakpoint on the post of create.But the function GetIDs() is correct.
What can I do please?

MVC 3 RAZOR - how to use hidden fields to maintain state of checkboxes between page request?

I am using Hidden fields to maintain the state of my checkboxes between page requests except it doesn't work. So when I click on my webgrid to go to the next 15 records it forgets which checkboxes are checked.
Index view
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#{
ViewBag.Title = "User Manager Dashboard";
}
#Html.ActionLink("Create New User", "CreateUser")
#using (#Html.BeginForm())
{
<div class="webgrid-filter">
#{Html.RenderAction("_WebGridFilter", "UserManager");}
</div>
<div id="webgrid-wrapper">
#Html.Partial("~/Views/Partial/_WebGridUserManager.cshtml", Model)
</div>
<br />
}
<script type="text/javascript">
$(document).ready(function () {
// Disable checkboxs where a user is not active.
$(".webgrid-wrapper input:not(:checked)").attr("disabled", "disabled");
// Style tables.
function jQueryUIStyling() {
$('input:button, input:submit').button();
$('.webgrid-wrapper').addClass('ui-grid ui-widget ui-widget-content ui-corner-all');
$('.webgrid-title').addClass('ui-grid-header ui-widget-header ui-corner-top');
jQueryTableStyling();
} // end of jQueryUIStyling
function jQueryTableStyling() {
$('.webgrid').addClass('ui-grid-content ui-widget-content');
$('.webgrid-header').addClass('ui-state-default');
$('.webgrid-footer').addClass('ui-grid-footer ui-widget-header ui-corner-bottom ui-helper-clearfix');
} // end of jQueryTableStyling
});
</script>
<script type="text/javascript">
function filterGrid() {
var filters = getFilterVals();
$.ajax({
url: '#Url.Action("Index", "UserManager")',
type: "POST",
async: true,
dataType: "html",
data: "alfConnect=" + filters.alfConnect + "&" + "alfIntelligence=" + filters.alfIntelligence + "&" + "brad=" + filters.brad,
success: function (data) {
$('#webgrid-wrapper').empty().html(data);
// $('#webgrid-wrapper').html(data);
}
});
}
function getFilterVals() {
filters = new Object();
if ($('.webgrid-filter #chkFilterAlfIntell').is(':checked')) {
filters.alfIntelligence = 1;
}
else {
filters.alfIntelligence = 0;
}
if ($('.webgrid-filter #chkFilterAlfConn').is(':checked')) {
filters.alfConnect = 1;
}
else {
filters.alfConnect = 0;
}
if ($('.webgrid-filter #chkFilterBrad').is(':checked')) {
filters.brad = 1;
}
else {
filters.brad = 0;
}
return filters;
}
function logUserOff(url) {
var answer = confirm('Are you sure you want to save this data?')
if (answer) {
// alert(url + ": " + value);
$.ajax({
url: url,
type: "POST"
// data: value
}).done(function () {
$(this).addClass("done");
});
return true;
}
else {
return false;
}
};
</script>
Partial view with hidden fields
#model UserManager.Models.webgrid_validation
<b>#Html.Label("Select a filter: ")</b>
<br />
#Html.Label("Toggle ALF Intelligence users:")
#Html.CheckBoxFor(model => model.chkBoxAlfIntelligence, new
{
id = "chkFilterAlfIntell",
onclick = "filterGrid()",
#checked = "checked"
})
#Html.Hidden("hdnAlfIntelligence", Model.chkBoxAlfIntelligence)
#Html.Label("Toggle ALF Connect users:")
#Html.CheckBoxFor(model => model.chkBoxAlfConnect, new
{
id = "chkFilterAlfConn",
onclick = "filterGrid()",
#checked = "checked"
})
#Html.Hidden("hdnAlfConnect", Model.chkBoxAlfConnect)
#Html.Label("Toggle BRAD users:")
#Html.CheckBoxFor(model => model.chkBoxBrad, new
{
id = "chkFilterBrad",
onclick = "filterGrid()",
#checked = "checked"
})
#Html.Hidden("hdnBrad", Model.chkBoxBrad)
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManager.Models;
namespace UserManager.Controllers
{
public class UserManagerController : Controller
{
//
// GET: /UserManager/
public ActionResult Index()
{
try
{
var model = new UserManagerTestEntities().vw_UserManager_Model;
return View(model.ToList());
}
catch (Exception ex)
{
return View(ViewBag);
}
}
[HttpPost]
public ActionResult Index(int alfConnect, int alfIntelligence, int brad)
{
List<UserManager.Models.vw_UserManager_Model> modelList = DAL.getGrid(alfConnect, alfIntelligence, brad);
switch (alfConnect)
{
case 1:
ViewData["chkBoxAlfConnect"] = 1;
break;
case 0:
ViewData["chkBoxAlfConnect"] = 0;
break;
}
switch (alfIntelligence)
{
case 1:
ViewData["chkBoxAlfIntelligence"] = 1;
break;
case 0:
ViewData["chkBoxAlfIntelligence"] = 0;
break;
}
switch (brad)
{
case 1:
ViewData["chkBoxBrad"] = 1;
break;
case 0:
ViewData["chkBoxBrad"] = 0;
break;
}
return PartialView("~/Views/Partial/_WebGridUserManager.cshtml", modelList);
}
[ChildActionOnly]
public ActionResult _WebGridFilter ()
{
UserManager.Models.webgrid_validation model = new webgrid_validation();
return PartialView("~/Views/Partial/_WebGridFilter.cshtml", model);
}
//public ActionResult _WebGridFilter(int alfConnect, int alfIntelligence, int brad)
//{
// UserManager.Models.webgrid_validation model = new webgrid_validation();
//switch (alfConnect)
//{
// case 1:
// model.chkBoxAlfConnect = true;
// break;
// case 0:
// model.chkBoxAlfConnect = false;
// break;
//}
//switch (alfIntelligence)
//{
// case 1:
// model.chkBoxAlfIntelligence = true;
// break;
// case 0:
// model.chkBoxAlfIntelligence = false;
// break;
//}
//switch (brad)
//{
// case 1:
// model.chkBoxBrad = true;
// break;
// case 0:
// model.chkBoxBrad = false;
// break;
//}
// return PartialView("~/Views/Partial/_WebGridFilter.cshtml", model);
//}
#region ajaxMethods
public ActionResult LookUpGroupName(string q, int limit)
{
try
{
//TODO: Map list to autocomplete textbox control
DAL d = new DAL();
List<string> groups = d.groups();
var GroupValue = groups
.Where(x => x.Contains(q))
.OrderBy(x => x)
.Take(limit)
.Select(r => new { group = r });
// Return the result set as JSON
return Json(GroupValue, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return View(ex.ToString());
}
}
public ActionResult LogUserOff(string userid)
{
try
{
//TODO: Map list to autocomplete textbox control
return View();
}
catch (Exception ex)
{
return View(ex.ToString());
}
}
//[HttpPost]
//public ActionResult FilterGrid(int alfConnect, int alfIntelligence, int brad)
//{
// List<UserManager.Models.vw_UserManager_Model> modelList = DAL.getGrid(alfConnect, alfIntelligence, brad);
// return PartialView("_WebGridUserManager", modelList);
//}
#endregion
#region crud
public ActionResult CreateUser()
{
//var data = new UserManager.Models.UserManagerTestEntities();
ViewBag.Message = "Create New User";
var model = new vw_UserManager_Model();
return View(model);
}
[HttpPost]
public ActionResult CreateUser (vw_UserManager_Model model)
{
int outcome = 0;
if (ModelState.IsValid)
{
//var data = new UserManager.Models.UserManagerTestEntities();
// Pass model to Data Layer
outcome = UserManager.DAL.CreateUser(model, outcome);
//data.SaveChanges();
}
if (outcome > 0) // Success
{
return RedirectToAction("showSuccess", model);
}
else // Failure
{
return RedirectToAction("showError", new { ErrorMessage = "Error" });
}
}
public ActionResult EditUser(Guid userid, string salutation, string firstname, string lastname, string password, Nullable<bool> isactive, Nullable<int> maxconcurrentusers, string email, string module, string group)
{
vw_UserManager_Model editUser = new vw_UserManager_Model();
editUser.userid = userid;
editUser.salutation = salutation;
editUser.firstname = firstname;
editUser.lastname = lastname;
editUser.password = password;
editUser.isactive = isactive;
editUser.MaxConcurrentUsers = maxconcurrentusers;
editUser.email = email;
editUser.module_name = module;
editUser.group_name = group;
return View(editUser);
}
[HttpPost]
public ActionResult EditUser(vw_UserManager_Model editUser)
{
if (ModelState.IsValid)
{
UserManager.DAL.EditUser(editUser);
}
return View();
}
public ActionResult DeleteUser(Guid userid, string username, string salutation, string firstname, string lastname, string password, bool isactive, string email, string module, string group)
{
vw_UserManager_Model DeleteUser = new vw_UserManager_Model();
DeleteUser.userid = userid;
DeleteUser.UserName = username;
DeleteUser.salutation = salutation;
DeleteUser.firstname = firstname;
DeleteUser.lastname = lastname;
DeleteUser.password = password;
DeleteUser.isactive = isactive;
DeleteUser.email = email;
DeleteUser.module_name = module;
DeleteUser.group_name = group;
return View(DeleteUser);
}
[HttpPost]
public ActionResult DeleteUser(vw_UserManager_Model deleteUser)
{
if (ModelState.IsValid)
{
UserManager.DAL.DeleteUser(deleteUser);
return RedirectToAction("showSuccess", new { SuccessMessage = "Success" });
}
return View();
}
#endregion crud
#region successErrorHandling
public ActionResult showError(List<string> ErrorMessage)
{
ViewBag.ErrorMessage = ErrorMessage[0];
return View("ErrorMessageView");
}
public ActionResult showSuccess(vw_UserManager_Model model)
{
return View("SuccessMessageeView", model);
}
#endregion
}
}
My question is how to use hidden fields to maintain state of checkboxes between page request?
you could remove the form and send data to the controller as JSon values, and thus refresh only the part of the page that needs to be refreshed.
Regards

string array to be separated with comma

I had a string array which I want it to be returned in view separated by comma.
#Html.DisplayFor(m => name.studentName) <span>, </span>}
I'm using this way but the last string will ended with a comma also. Wondering how to avoid this?
I assume that you have a collection of students on your model each possessing a studentName property that you want to display:
public IEnumerable<Student> Students { get; set; }
And inside your view you are looping through this collection and displaying each student name individually.
Now instead of looping you could do the following:
#Html.Raw(
string.Join(
"<span>,<span>",
Model.Students.Select(x => Html.Encode(x.studentName))
)
)
or even better, externalize this logic into a reusable custom HTML helper:
public static class HtmlExtensions
{
public static IHtmlString FormatStudentNames(this HtmlHelper htmlHelper, IEnumerable<Student> students)
{
return new HtmlString(
string.Join(
"<span>,<span>",
students.Select(x => Html.Encode(x.studentName))
)
);
}
}
and then inside your view simply call this helper:
#Html.FormatStudentNames(Model.Students)
You no longer need to write any foreach or whatever loops you are writing.
Try
#string.Join(",", name.studentName);
And have a look at string.Join on MSDN.
$(".category").change(function () {
var value = $(this).val();
loadSubCategory(value)
});
function loadSubCategory(parentID) {
var $el = $("#SubCats");
$el.prop("disabled", true);
$el.empty();
$.ajax({
cache: false,
url: "/Category/loadSubCategory?id=" + parentID,
success: function (data) {
if (data != '' && data != null) {
if (data != 'error') {
var sch = JSON.parse(data);
if (sch.length > 0) {
$el.prop("disabled", false);
for (i = 0; i < sch.length; i++) {
$el.append($("<option></option>")
.attr("value", sch[i].ID).text(sch[i].Description));
}
}
}
}
}
});
}
public ActionResult loadSubCategory(string id)
{
string list = "";
try
{
list = Newtonsoft.Json.JsonConvert.SerializeObject(menu.SubCategory(id));
}
catch (Exception ex)
{
}
return Content(list);
}
public List<CategoryModel> SubCategory(string parentID){
List<CategoryModel> listCategory= new List<CategoryModel>();
string[] yourValues = parentID.Split(',');
foreach (var item in yourValues)
{
var Category = UowObj.CategoryRepository.Get(filter: c => c.ParentId.ToString() == item && c.IsActive == true).ToList();
if (Category != null)
{
var category= new CategoryModel();
foreach (var itemq in Category)
{
category.ID = itemq.ID;
category.Description = itemq.Description;
}
listCategory.Add(merchant);
}
}

How to get selected value and and id from dropdownlist in mvc3?

When I make my httppost call, i need to get the selected value and the id of a random number of dropdownlists in my view. The number of dropdownlists is random because they are created dynamically based on the selected value of another dropdownlist.
Example:
in dropdownlist 1 I select bmw. Then 3 dropdownlists are created, so the user can give each carmodel a rate value. Each dropdownlist has id= the model of the car and the options you can select is 1,2 and 3. If there was 4 carmodels of bmw, the options would then be 1,2,3 and 4 and so on...
When I make the httppost call, how do I in the controller run through all the dynammically created dropdownlist and check the value and id?
EDIT:
The controller of my index view:
public class BookingPensionController : Controller
{
private DbEntities db = new DbEntities();
EditBookingPensionViewModel objViewModel;
public ActionResult Index()
{
objViewModel = new EditBookingPensionViewModel
{
Booking = new Booking { BookingStartDate = DateTime.Today, BookingEndDate = DateTime.Today, DateOfBooking = DateTime.Now }
};
objViewModel.deliveryTypes = new List<string>();
int id = int.Parse(Session["id"].ToString());
SelectList list;
try
{
var deliverytypes = from d in db.DeliveryTypes
where d.Pension_ID == id
select d;
foreach (DeliveryType item in deliverytypes)
{
objViewModel.deliveryTypes.Add(item.Titel);
}
ViewData["DeliveryTypes"] = objViewModel.deliveryTypes;
objViewModel.customersToPension = new List<SelectListItem>();
objViewModel.customersToPension = GetCustomersToPension(id);
}
catch (Exception ex)
{
throw;
}
int PensionId = int.Parse(Session["id"].ToString());
objViewModel.CustomerValue = GetCustomersToPension(PensionId);
return View(objViewModel);
}
My Index view:
#model HundePensionBooking.ViewModels.EditBookingPensionViewModel
//Some code...
//And my script that retreives the customerinfo and creates the dropdownlists
$("#ddlCustomerId").change(function () {
var id = $("#ddlCustomerId").val();
getCustomerInfo(id);
$('#customerinfo').load("#Url.Action("CustomerInfo", "BookingPension")");
var ddlsource = "#ddlCustomerId";
var ddltarget = "#ddlDogId";
$.getJSON('#Url.Action("Dogs_SelectedCustomer")', { CustomerId: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$("#tblRooms tr:gt(0)").remove();
$.each(data, function (index, optionData) {
createDynamicTable($("#tblRooms"), optionData.Text, data.length);
});
});
});
});
</script>
<script type="text/javascript">
function createDynamicTable(tbody, value, count) {
if (tbody == null || tbody.length < 1) return;
var trow = $("<tr>");
var cellText = value
var option;
$('<th scope="row" abbr="Model" class="spec">')
.addClass("tableCell")
.text(cellText)
.appendTo(trow);
var ddlselectroom = '<td class="spectd"><select class="selectbox" id=' + value + '>';
for (var d = 1; d <= count; d++) {
ddlselectroom += '<option value="' + d + '">Bur nr. ' + d + '</option>';
}
ddlselectroom += '</select></td>';
$(ddlselectroom).appendTo(trow);
trow.appendTo(tbody);
}
//Some more code...
//And then the table which gets populated with the random number of dropdownlists:
<table id="tblRooms" width="100%">
<tr>
</tr>
</table>
The Viewmodel looks like this:
public class EditBookingPensionViewModel
{
public Booking Booking { get; set; }
public IEnumerable<Customer> customerList { get; set; }
public List<string> deliveryTypes { get; set; }
public List<SelectListItem> customersToPension { get; set; }
public Customer customer { get; set; }
public CustomerInfoModel CustomerInfo { get; set; }
My partialview with the customerinfo looks like this:
#model HundePensionBooking.Models.Customer
So when I make the httppost call
<input type="submit" value="Create" />
I need to get all the data down to my database. Im not sure on how to do that but I assume I have to do it with my Create method in the controller class
[HttpPost]
public ActionResult Create(EditBookingPensionViewModel model)
{
//SaveCustomer... From the CustomerInfo partialview
//SaveBooking...From Index view
//Save all the data from all the dropdownlists... from index view
}
just add a hidden field of counter, when you submit, get value of counter then loop from 1 to value of counter and request optionname + counter. jquery should be used to set the value of counter.

Resources