public static void GetLocationSelectedListItem(IList<Location> locations, out MultiSelectList allLocation, out List<SelectListItem> selectListItems) { var multiSelectList = new MultiSelectList(locations, "LocationId", "Province", locations); allLocation = multiSelectList; selectListItems = locations.Select(o => new SelectListItem { Text = o.Province, Value = o.Province }).ToList(); }
public UserRolesViewModel MapUserRoles(UserProfile user, IList<UserRole> roles) { if (user == null) return new UserRolesViewModel(); var view = new UserRolesViewModel { FirstName = user.FirstName, LastName = user.LastName, UserName = user.UserName, Roles = new List<RolesViewModel>() }; foreach (UserRole role in roles) { RolesViewModel roleView = Mapper.Map<UserRole, RolesViewModel>(role); foreach (UserRole userRole in user.Roles) { roleView.IsChecked = userRole.Id == role.Id; } view.Roles.Add(roleView); } var selectRoles = new MultiSelectList(view.Roles, "RoleId", "RoleName", view.Roles .Where(x => x.IsChecked) .Select(x =>x.RoleId)); view.MultiSelectRoles = selectRoles; return view; }
public void FilterByTags(ViewDataDictionary viewData, int[] selectedTagsIds, IEnumerable<Tag> tags) { if (selectedTagsIds != null && selectedTagsIds[0] != 0) { var selectedTags = tags.Where(e => selectedTagsIds.Contains(e.TagID)).ToList(); viewData["TagsFilter"] = new MultiSelectList(tags, "TagID", "Name", selectedTags); var tempConferences = new List<Conference>(); foreach (var conference in Conferences) { foreach (var selectedTagId in selectedTagsIds) { if (conference.Tags.Any(e => e.TagID == selectedTagId)) { if (!tempConferences.Contains(conference)) { tempConferences.Add(conference); } } } } Conferences = tempConferences; } }
public ActionResult Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var user = UserManager.FindById(id); if (user == null) { return HttpNotFound(); } var db = new ApplicationDbContext(); var userx = new UserViewModel { BranchId = user.BranchId, Name = user.UserName, Roles = user.Roles.Select(p => p.Role.Name).ToList(), AvailableRoles = db.Roles.ToList() }; var m = new MultiSelectList(db.Roles.ToList(), "Name", "Name"); ViewBag.Roles = m; var x = new SelectList(db.Branches.ToList(), "Id", "Name"); ViewBag.Branches = x; return View(userx); }
public ArticleModel() : base() { SubTitle = "Holy Angels Article(s)"; PageTitle = "Articles"; Ministries = new List<MinistryModel>(); MultiSelectMinistryList = new MultiSelectList(new List<MinistryModel>()); }
/// <summary>Generate a control for a set preference.</summary> private static string SetPreferenceControl(HtmlHelper helper, MetaAttribute ma, Preference preference) { string result; if (ma.HasChoices) { if (preference != null) { MultiSelectList listData = new MultiSelectList(SelectHelper.DropDownRecordsFromValueSet(ma.ChoicesCollection), "Value", "Text", SelectHelper.ValuesFromValueSet(preference.Set)); result = helper.ListBox(ma.PreferenceSetControlName, listData); } else { MultiSelectList listData = new MultiSelectList(SelectHelper.DropDownRecordsFromValueSet(ma.ChoicesCollection), "Value", "Text"); result = helper.ListBox(ma.PreferenceSetControlName, listData); } } else { if (preference != null) { result = helper.TextBox(ma.PreferenceSetControlName, preference.RawValues); } else { result = helper.TextBox(ma.PreferenceSetControlName); } } return result; }
public MinistryModel() : base() { PageTitle = "Holy Angels Ministries"; SubTitle = "Ministries"; Users = new List<UserModel>(); MultiSelectUserList = new MultiSelectList(new List<UserModel>()); }
public ActionResult ClinicsList(string ID) { List<SelectListItem> listClinic = new List<SelectListItem>(); if (ID == "ALL") { var itemsClinic = dbm.vwContract_Clinic_Analysis_ClinicMaterial_ForReports.Select(o => new { o.ClinicContractID, o.ClinicDesc, o.ClinicGroupDesc, o.ContractDesc }).Distinct().OrderBy(o => o.ContractDesc ).ToList(); listClinic.Add(new SelectListItem { Text = "Все ЛПУ", Value = "ALL" }); foreach (var item in itemsClinic) { listClinic.Add(new SelectListItem { Text = item.ContractDesc + " - " + item.ClinicGroupDesc + " - " + item.ClinicDesc, Value = item.ClinicContractID.ToString() }); } } else { var itemsClinic = dbm.vwContract_Clinic_Analysis_ClinicMaterial_ForReports.Where(o => o.ContractDesc == ID).Select(o => new { o.ClinicContractID, o.ClinicDesc, o.ClinicGroupDesc, o.ContractDesc }).Distinct().OrderBy(o => o.ContractDesc ).ToList(); listClinic.Add(new SelectListItem { Text = "Все ЛПУ", Value = "ALL" }); foreach (var item in itemsClinic) { listClinic.Add(new SelectListItem { Text = item.ContractDesc + " - " + item.ClinicGroupDesc + " - " + item.ClinicDesc, Value = item.ClinicContractID.ToString() }); } } var selectClinic = new MultiSelectList(listClinic, "Value", "Text", "ALL"); if (HttpContext.Request.IsAjaxRequest()) return Json(selectClinic, JsonRequestBehavior.AllowGet); return RedirectToAction("Index"); }
public ArchitecturalStrategyViewModel(ArchitecturalStrategy strategy) { var scenarioRepository = new ScenarioRepository(); var strategyRepository = new ArchitecturalStrategyRepository(); Strategy = strategy; Strategy.Description = strategy.Description == null ? null : strategy.Description.Trim(); AffiliatedScenarios = strategyRepository.GetAffiliatedScenariosByStratID(strategy.ID).OrderBy(x => x.Priority); //scenarios (in top 6th) not affiliated with strategy var slistNotUsed = scenarioRepository.GetTopSixth(strategy.ProjectID).OrderBy(x => x.Priority).ToList(); //new scenario if (strategy != null && strategy.ID !=0) //set used for existing scenario { slistNotUsed = scenarioRepository.GetTopSixth(strategy.ProjectID) .Where(a => !Strategy.ExpectedUtilities.Select(x => x.Scenario.ID).Contains(a.ID)).OrderBy(x => x.Priority).ToList(); } //scenarios affiliated with strategy // var slistused = scenarioRepository.GetTopSixth(strategy.ProjectID) // .Where(a => strategy.ExpectedUtilities // .Select(x => x.ScenarioID). //Select Scenario IDs // Contains(a.ID)).ToList(); //a.ID = //needs to be list of availble scenarios, exclude already selected //(theObjList, value, text to show, pre-SelectedItems) ScenarioSelectList = new MultiSelectList(slistNotUsed, "ID", "Name", strategy.ExpectedUtilities.Select(x => x.ScenarioID)); ScenariosSelectedList = new MultiSelectList(AffiliatedScenarios, "ID", "Name", strategy.ExpectedUtilities.Select(x => x.ScenarioID)); strategyForExpectedResponse = populateStrategyForExpectedResponse(strategy, AffiliatedScenarios); }
public IndexViewModel() { ConsentValidFromStart = new OptionalDateInputViewModel(allowPastDates: true, showLabels: false); ConsentValidFromEnd = new OptionalDateInputViewModel(allowPastDates: true, showLabels: false); ConsentValidToStart = new OptionalDateInputViewModel(allowPastDates: true, showLabels: false); ConsentValidToEnd = new OptionalDateInputViewModel(allowPastDates: true, showLabels: false); NotificationReceivedStart = new OptionalDateInputViewModel(allowPastDates: true, showLabels: false); NotificationReceivedEnd = new OptionalDateInputViewModel(allowPastDates: true, showLabels: false); NotificationTypes = new SelectList(EnumHelper.GetValues(typeof(NotificationType)), dataTextField: "Value", dataValueField: "Key"); TradeDirections = new SelectList(EnumHelper.GetValues(typeof(TradeDirection)), dataTextField: "Value", dataValueField: "Key"); InterimStatus = new SelectList(new[] { new SelectListItem { Text = "Interim", Value = "true" }, new SelectListItem { Text = "Non-interim", Value = "false" } }, dataTextField: "Text", dataValueField: "Value"); OperationCodes = new MultiSelectList(EnumHelper.GetValues(typeof(OperationCode)), dataTextField: "Value", dataValueField: "Key"); NotificationStatuses = new SelectList(GetCombinedNotificationStatuses(), dataTextField: "Name", dataValueField: "StatusId", dataGroupField: "TradeDirection", selectedValue: null); SelectedOperationCodes = new OperationCode[] { }; }
public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, MultiSelectList listInfo, IDictionary<string, object> htmlAttributes) { if (String.IsNullOrEmpty(name)) throw new ArgumentException("The argument must have a value", "name"); if (listInfo == null) throw new ArgumentNullException("listInfo"); if (listInfo.Count() < 1) throw new ArgumentException("The list must contain at least one value", "listInfo"); StringBuilder sb = new StringBuilder(); foreach (SelectListItem info in listInfo) { TagBuilder builder = new TagBuilder("input"); if (info.Selected) builder.MergeAttribute("checked", "checked"); builder.MergeAttributes<string, object>(htmlAttributes); builder.MergeAttribute("type", "checkbox"); builder.MergeAttribute("value", info.Value); builder.MergeAttribute("name", name); builder.InnerHtml = info.Text; sb.Append(builder.ToString(TagRenderMode.Normal)); sb.Append("<br />"); } return MvcHtmlString.Create(sb.ToString()); }
public ActionResult Create([Bind(Include = "Name,LocationTypeId,CrimeTypeIds")]CrimeLocationTypeFormViewModel crimeLocationTypeForm) { if (ModelState.IsValid) { CrimeLocationTypeEntity crimeLocationTypeEntity = new CrimeLocationTypeEntity(); crimeLocationTypeEntity.Name = crimeLocationTypeForm.Name; crimeLocationTypeEntity.LocationType = _locationTypeService.GetLocationTypeById(crimeLocationTypeForm.LocationTypeId); crimeLocationTypeEntity.LocationTypeId = crimeLocationTypeForm.LocationTypeId; crimeLocationTypeEntity.CrimeTypes = new List<CrimeTypeEntity>(); foreach (var crimeTypeId in crimeLocationTypeForm.CrimeTypeIds) { crimeLocationTypeEntity.CrimeTypes.Add(_crimeTypeService.GetCrimeTypeById(crimeTypeId)); } _crimeLocationTypeService.CreateCrimeLocationType(crimeLocationTypeEntity); return RedirectToAction("Index"); } List<LocationTypeEntity> dbLocationTypeModels = _locationTypeService.GetAllLocationTypes().ToList(); List<CrimeTypeEntity> dbCrimeTypeModels = _crimeTypeService.GetAllCrimeTypes().ToList(); ViewData["LocationTypes"] = new SelectList(dbLocationTypeModels, "LocationTypeId", "Name"); ViewData["CrimeTypes"] = new MultiSelectList(dbCrimeTypeModels, "CrimeTypeId", "Name"); return View(crimeLocationTypeForm); }
public ActionResult Create() { var newEmployee = new Employee(); ViewData["Projects"] = new MultiSelectList(_employeeService.GetAllProjects(), "ProjectId", "ProjectName"); ViewData["Skills"] = new MultiSelectList(_employeeService.GetAllSkillSets(), "SkillSetId", "Name"); //ViewBag.Skills = new MultiSelectList(_employeeService.GetAllRoles(), "Id", "Name"); return View(newEmployee); }
public UserModel() { UserStatus = UserStatus.Offline; Roles = new List<RoleModel>(); Ministries = new List<MinistryModel>(); MultiSelectRoleList = new MultiSelectList(new List<RoleModel>()); MultiSelectMinistryList = new MultiSelectList(new List<MinistryModel>()); }
// GET: Management/CrimeLocationType/Create public ActionResult Create() { List<LocationTypeEntity> dbLocationTypeModels = _locationTypeService.GetAllLocationTypes().ToList(); List<CrimeTypeEntity> dbCrimeTypeModels = _crimeTypeService.GetAllCrimeTypes().ToList(); ViewData["LocationTypes"] = new SelectList(dbLocationTypeModels, "LocationTypeId", "Name"); ViewData["CrimeTypes"] = new MultiSelectList(dbCrimeTypeModels, "CrimeTypeId", "Name"); return View(); }
public void GetListItemsThrowsOnBindingFailure() { // Arrange MultiSelectList multiSelect = new MultiSelectList(GetSampleFieldObjects(), "Text", "Value", new string[] { "A", "C", "T" }); // Assert ExceptionHelper.ExpectHttpException( delegate { IList<SelectListItem> listItems = multiSelect.GetListItems(); }, "DataBinding: 'System.Web.Mvc.Test.MultiSelectListTest+Item' does not contain a property with the name 'Text'.", 500); }
/// <summary> /// Default constructor. Creates a new model. /// </summary> /// <param name="isfolder">Weather this is a folder or not.</param> public EditModel(bool isfolder, Guid parentid) { Content = new Piranha.Models.Content() { IsFolder = isfolder, ParentId = parentid } ; ContentCategories = new List<Guid>() ; Categories = new MultiSelectList(Category.GetFields("category_id, category_name", new Params() { OrderBy = "category_name" }), "Id", "Name") ; var folders = Content.GetFields("content_id, content_name", "content_folder=1", new Params() { OrderBy = "content_name" }) ; folders.Insert(0, new Content()) ; if (Content.ParentId == Guid.Empty) Folders = new SelectList(folders, "Id", "Name") ; else Folders = new SelectList(folders, "Id", "Name", Content.ParentId) ; }
/// <summary> /// Default constructor. Creates a new model. /// </summary> /// <param name="isfolder">Whether this is a folder or not.</param> public EditModel(bool isfolder, Guid parentid) { Content = new Piranha.Models.Content() { IsFolder = isfolder, ParentId = parentid } ; ContentCategories = new List<Guid>() ; Categories = new MultiSelectList(Category.GetFields("category_id, category_name", new Params() { OrderBy = "category_name" }), "Id", "Name") ; var folders = Content.GetFields("content_id, content_name", "content_folder=1 AND content_draft=1", new Params() { OrderBy = "content_name" }) ; folders.Insert(0, new Content()) ; Extensions = Content.GetExtensions() ; Folders = SortFolders(Content.GetFolderStructure(false)) ; Folders.Insert(0, new Placement() { Text = "", Value = Guid.Empty }) ; }
/// <summary> /// Default constructor. /// </summary> public EditModel() { Post = new Post(); PostCategories = new List<Guid>(); Properties = new List<Property>(); Extensions = new List<Extension>(); AttachedContent = new List<Paladino.Models.Content>(); Content = Paladino.Models.Content.Get(); Comments = new List<Entities.Comment>(); Categories = new MultiSelectList(Category.GetFields("category_id, category_name", new Params() { OrderBy = "category_name" }), "Id", "Name"); }
public static MultiSelectList GetAllGenres(StoreContext context) { var genres = from g in context.Genre orderby g.Name select g; List<Genre> allGenres = genres.ToList(); MultiSelectList genreList = new MultiSelectList(allGenres, "GenreID", "Name"); return genreList; }
public void Constructor3SetsProperties() { // Arrange IEnumerable items = new object[0]; // Act MultiSelectList multiSelect = new MultiSelectList(items, "SomeValueField", "SomeTextField"); // Assert Assert.AreSame(items, multiSelect.Items); Assert.AreEqual("SomeValueField", multiSelect.DataValueField); Assert.AreEqual("SomeTextField", multiSelect.DataTextField); Assert.IsNull(multiSelect.SelectedValues); }
public ActionResult Index() { vwReportIndex model = new vwReportIndex(); var itemsContract = dbm.vwContract_Clinic_Analysis_ClinicMaterial_ForReports.Select(o => new { o.ContractID, o.ContractDesc }).Distinct().OrderBy(o => o.ContractDesc).ToList(); List<SelectListItem> listContract = new List<SelectListItem>(); listContract.Add(new SelectListItem { Text = "Все контракты", Value = "ALL" }); foreach (var item in itemsContract) { listContract.Add(new SelectListItem { Text = item.ContractDesc, Value = item.ContractID.ToString() }); } var selectContract = new MultiSelectList(listContract, "Value", "Text", "ALL"); ViewData["selectContract"] = selectContract; var itemsClinic = dbm.vwContract_Clinic_Analysis_ClinicMaterial_ForReports.Select(o => new { o.ClinicContractID, o.ClinicDesc, o.ClinicGroupDesc, o.ContractDesc }).Distinct().OrderBy(o => o.ClinicGroupDesc).ToList(); List<SelectListItem> listClinic = new List<SelectListItem>(); listClinic.Add(new SelectListItem { Text = "Все ЛПУ", Value = "ALL" }); foreach (var item in itemsClinic) { listClinic.Add(new SelectListItem { Text =item.ContractDesc + " - " + item.ClinicGroupDesc + " - " + item.ClinicDesc, Value = item.ClinicContractID.ToString() }); } var selectClinic = new MultiSelectList(listClinic, "Value", "Text", "ALL"); ViewData["selectClinic"] = selectClinic; var itemsMBAnalysis = dbm.vwContract_Clinic_Analysis_ClinicMaterial_ForReports.Select(o => new { o.MBAnalysisTypeID, o.MBAnalysisDesc }).Distinct().OrderBy(o => o.MBAnalysisDesc).ToList(); List<SelectListItem> listMBAnalysis = new List<SelectListItem>(); listMBAnalysis.Add(new SelectListItem { Text = "Все анализы", Value = "ALL" }); foreach (var item in itemsMBAnalysis) { listMBAnalysis.Add(new SelectListItem { Text = item.MBAnalysisDesc, Value = item.MBAnalysisTypeID.ToString() }); } var selectMBAnalysis = new MultiSelectList(listMBAnalysis, "Value", "Text", "ALL"); ViewData["selectMBAnalysis"] = selectMBAnalysis; var itemsClinicMaterial = dbm.vwContract_Clinic_Analysis_ClinicMaterial_ForReports.Select(o => new { o.ClinicMaterialID, o.ClinicMaterialDesc }).Distinct().OrderBy(o => o.ClinicMaterialDesc).ToList(); List<SelectListItem> listClinicMaterial = new List<SelectListItem>(); listClinicMaterial.Add(new SelectListItem { Text = "Все клин.материалы", Value = "ALL" }); foreach (var item in itemsClinicMaterial) { listClinicMaterial.Add(new SelectListItem { Text = item.ClinicMaterialDesc, Value = item.ClinicMaterialDesc.ToString() }); } var selectClinicMaterial = new MultiSelectList(listClinicMaterial, "Value", "Text", "ALL"); ViewData["selectClinicMaterial"] = selectClinicMaterial; model.dateStart = DateTime.Now.ToShortDateString(); model.dateEnd = DateTime.Now.ToShortDateString(); return View(model); }
public static HtmlString CheckBoxList(this IHtmlHelper htmlHelper, string name, MultiSelectList listInfos, int iPosition) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("This parameter cannot be null or empty!", "name"); } if (listInfos == null) { throw new ArgumentException("This parameter cannot be null!", "listInfos"); } //if (listInfos.Count<SelectListItem>() < 1) //{ // throw new ArgumentException("The count must be greater than 0!", "listInfos"); //} List<string> selectedValues = (List<string>)listInfos.SelectedValues; List<TagBuilder> lsTagBuilders = new List<TagBuilder>(); int lineNumber = 0; foreach (SelectListItem info in listInfos) { lineNumber++; TagBuilder builder = new TagBuilder("input"); if (selectedValues.Contains(info.Value)) { builder.MergeAttribute("checked", "checked"); } builder.MergeAttribute("type", "checkbox"); builder.MergeAttribute("name", name); builder.MergeAttribute("value", info.Value); builder.InnerHtml.AppendHtml(info.Text); if (iPosition == 0) { builder.InnerHtml.AppendHtml("<br />"); ; } lsTagBuilders.Add(builder); } using (var writer = new StringWriter()) { foreach (TagBuilder oTagBuilder in lsTagBuilders) oTagBuilder.WriteTo(writer, new HtmlEncoder()); return new HtmlString(writer.ToString()); } }
public void Constructor3SetsProperties_SelectedValues_DisabledValues() { // Arrange IEnumerable items = new[] { "A", "B", "C" }; IEnumerable selectedValues = new[] { "A", "C" }; IEnumerable disabledValues = new[] { "B", "C" }; // Act MultiSelectList multiSelect = new MultiSelectList(items, selectedValues, disabledValues); // Assert Assert.Same(items, multiSelect.Items); Assert.Equal(selectedValues, multiSelect.SelectedValues); Assert.Equal(disabledValues, multiSelect.DisabledValues); Assert.Null(multiSelect.DataTextField); Assert.Null(multiSelect.DataValueField); }
public ActionResult Edit(int id) { User user = userService.GetById(id); if (user == null) { return HttpNotFound(); } MultiSelectList roles = new MultiSelectList(roleService.GetAll().Select(role => role.Name)); UserEditViewModel userModel = new UserEditViewModel() { Id = user.Id, Username = user.Email, Roles = user.Roles.Select(r => r.Name).ToList() }; ViewBag.Roles = roles; return View(userModel); }
public static MultiSelectList BuildSortedMultiList(dynamic p_viewBag, object p_model) { IEnumerable l_items = null; if (p_viewBag.RelatedEntityId != null) { OrderedDictionary l_params = new OrderedDictionary(); l_params.Add("relatedEntityId", p_viewBag.RelatedEntityId.ToString()); l_items = BuildEnumerable(p_viewBag.EntityTypeName, p_viewBag.ChoiceMethodName, false, l_params); } else { l_items = BuildEnumerable(p_viewBag.EntityTypeName, p_viewBag.ChoiceMethodName, false); } MultiSelectList l_list = new MultiSelectList(l_items.Cast<object>().OrderBy(o => DataBinder.Eval(o, ViewPropertyDescriptor.EntityDisplayName)), ViewPropertyDescriptor.EntityKey, ViewPropertyDescriptor.EntityDisplayName, BuildSelectedEnumerable(p_model as IEnumerable)); return l_list; }
public ActionResult Create(Employee newEmployee) { try { ViewData["Projects"] = new MultiSelectList(_employeeService.GetAllProjects(), "ProjectId", "ProjectName"); ViewData["Skills"] = new MultiSelectList(_employeeService.GetAllSkillSets(), "SkillSetId", "Name"); // TODO: Add insert logic here _employeeService.SaveEmployee(newEmployee); ViewBag.SavedEmployee = newEmployee.FirstName; return View("Success"); } catch { return View("Error"); } }
public void basic_select_renders_select_with_options_from_select_list() { var items = new List<FakeModel> { new FakeModel {Id = 1, Title = "One"}, new FakeModel {Id = 2, Title = "Two"}, new FakeModel {Id = 3, Title = "Three"} }; var selectedOptions = new List<int> { 1, 3 }; var selectList = new MultiSelectList(items, "Id", "Title", selectedOptions); var html = new MultiSelect("foo.Bar").Options(selectList).ToString(); var element = html.ShouldHaveHtmlNode("foo_Bar"); var optionNodes = element.ShouldHaveChildNodesCount(3); optionNodes[0].ShouldBeSelectedOption(items[0].Id, items[0].Title); optionNodes[1].ShouldBeUnSelectedOption(items[1].Id, items[1].Title); optionNodes[2].ShouldBeSelectedOption(items[2].Id, items[2].Title); }
/// <summary> /// Metoden henter ut to lister som sendes til viewet. Den ene er av brukere med tilgang, og den andre er med brukere som ikke har tilgang. /// Brukeren skal kunne velge i disse listene for å legge dem til i den andre listen. /// </summary> /// <param name="c"></param> /// <param name="u"></param> /// <param name="userName"></param> public ChannelFormViewModel(Chatroom c, List<Permitted_user> u, string userName) { userRep = new UserRepository(); channelRep = new ChannelRepository(); room = c; permittedUsers = u; allUsers = userRep.showUsersNotInChatroom(u); finalUsers = userRep.showUsersNotInChatroom(u); foreach (aspnet_User us in allUsers) // sjekker etter brukeren som laget chatroomet. For så å fjerne brukerobjektet fra en liste som blir sendt til viewet. { if (us.LoweredUserName == userName) finalUsers.Remove(us); } // Liste med brukere som ikke er tilatt i rommet newUsers = new MultiSelectList(finalUsers, "UserId", "UserName", selectedValuesUser); // Liste med brukere som er i rommet currentUsers = new MultiSelectList(userRep.showCurrentUsers(u), "UserId", "UserName", selectedValuesCurrentUser); /** * Skal brukes i Oblig 2 * * bannedUsers = b; bannedList = new MultiSelectList(channelRep.showBannedUsers(b), "UserId", "UserName", selectedValuesbannedUser); notBannedList = new MultiSelectList(channelRep.showUnBannedUsers(b), "UserId", "UserName", selectedValuesUnBannedUsers); */ }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pnlMain = new System.Windows.Forms.Panel(); this.tbcCondition = new System.Windows.Forms.TabControl(); this.tbpCondition = new System.Windows.Forms.TabPage(); this.grbCondition = new System.Windows.Forms.GroupBox(); this.cmbFilterObjectValue = new System.Windows.Forms.ComboBox(); this.cmbFilterOperator = new System.Windows.Forms.ComboBox(); this.txtTextFilterValue = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.dtpDateTimeFilterValue = new System.Windows.Forms.DateTimePicker(); this.txtNumberFilterValue = new Janus.Windows.GridEX.EditControls.NumericEditBox(); this.tbpMultiSelectList = new System.Windows.Forms.TabPage(); this.grbMultiSelectList = new System.Windows.Forms.GroupBox(); this.label3 = new System.Windows.Forms.Label(); this.multiSelectList = new MultiSelectList(); this.txtFilterCondition2 = new System.Windows.Forms.TextBox(); this.btnCleanFilter = new System.Windows.Forms.Button(); this.btnRemoveCondition = new System.Windows.Forms.Button(); this.btnAddCondition = new System.Windows.Forms.Button(); this.grbLogicalOperator = new System.Windows.Forms.GroupBox(); this.rbtOr = new System.Windows.Forms.RadioButton(); this.rbtAnd = new System.Windows.Forms.RadioButton(); this.trvFilterCondition = new System.Windows.Forms.TreeView(); this.cmbColumn = new System.Windows.Forms.ComboBox(); this.lblFilterColumn = new System.Windows.Forms.Label(); this.btnAccept = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.pnlMain.SuspendLayout(); this.tbcCondition.SuspendLayout(); this.tbpCondition.SuspendLayout(); this.grbCondition.SuspendLayout(); this.tbpMultiSelectList.SuspendLayout(); this.grbMultiSelectList.SuspendLayout(); this.grbLogicalOperator.SuspendLayout(); this.SuspendLayout(); // // pnlMain // this.pnlMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pnlMain.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pnlMain.Controls.Add(this.tbcCondition); this.pnlMain.Controls.Add(this.txtFilterCondition2); this.pnlMain.Controls.Add(this.btnCleanFilter); this.pnlMain.Controls.Add(this.btnRemoveCondition); this.pnlMain.Controls.Add(this.btnAddCondition); this.pnlMain.Controls.Add(this.grbLogicalOperator); this.pnlMain.Controls.Add(this.trvFilterCondition); this.pnlMain.Controls.Add(this.cmbColumn); this.pnlMain.Controls.Add(this.lblFilterColumn); this.pnlMain.Location = new System.Drawing.Point(0, 0); this.pnlMain.Name = "pnlMain"; this.pnlMain.Size = new System.Drawing.Size(521, 360); this.pnlMain.TabIndex = 2; // // tbcCondition // this.tbcCondition.Controls.Add(this.tbpCondition); this.tbcCondition.Controls.Add(this.tbpMultiSelectList); this.tbcCondition.Location = new System.Drawing.Point(16, 48); this.tbcCondition.Name = "tbcCondition"; this.tbcCondition.SelectedIndex = 0; this.tbcCondition.Size = new System.Drawing.Size(344, 106); this.tbcCondition.TabIndex = 1; // // tbpCondition // this.tbpCondition.Controls.Add(this.grbCondition); this.tbpCondition.Location = new System.Drawing.Point(4, 22); this.tbpCondition.Name = "tbpCondition"; this.tbpCondition.Size = new System.Drawing.Size(336, 80); this.tbpCondition.TabIndex = 0; this.tbpCondition.Text = "Condición"; // // grbCondition // this.grbCondition.Controls.Add(this.cmbFilterObjectValue); this.grbCondition.Controls.Add(this.cmbFilterOperator); this.grbCondition.Controls.Add(this.txtTextFilterValue); this.grbCondition.Controls.Add(this.label2); this.grbCondition.Controls.Add(this.label1); this.grbCondition.Controls.Add(this.dtpDateTimeFilterValue); this.grbCondition.Controls.Add(this.txtNumberFilterValue); this.grbCondition.Location = new System.Drawing.Point(0, 0); this.grbCondition.Name = "grbCondition"; this.grbCondition.Size = new System.Drawing.Size(336, 80); this.grbCondition.TabIndex = 9; this.grbCondition.TabStop = false; // // cmbFilterObjectValue // this.cmbFilterObjectValue.Location = new System.Drawing.Point(96, 16); this.cmbFilterObjectValue.Name = "cmbFilterObjectValue"; this.cmbFilterObjectValue.Size = new System.Drawing.Size(232, 21); this.cmbFilterObjectValue.TabIndex = 2; this.cmbFilterObjectValue.DropDown += new System.EventHandler(this.cmbFilterObjectValue_DropDown); // // cmbFilterOperator // this.cmbFilterOperator.Location = new System.Drawing.Point(96, 49); this.cmbFilterOperator.Name = "cmbFilterOperator"; this.cmbFilterOperator.Size = new System.Drawing.Size(129, 21); this.cmbFilterOperator.TabIndex = 6; // // txtTextFilterValue // this.txtTextFilterValue.Location = new System.Drawing.Point(96, 16); this.txtTextFilterValue.Name = "txtTextFilterValue"; this.txtTextFilterValue.Size = new System.Drawing.Size(232, 20); this.txtTextFilterValue.TabIndex = 4; this.txtTextFilterValue.Text = ""; // // label2 // this.label2.Location = new System.Drawing.Point(16, 49); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(80, 23); this.label2.TabIndex = 11; this.label2.Text = "Criterio :"; // // label1 // this.label1.Location = new System.Drawing.Point(16, 17); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(80, 23); this.label1.TabIndex = 10; this.label1.Text = "Valor a Filtrar :"; // // dtpDateTimeFilterValue // this.dtpDateTimeFilterValue.Location = new System.Drawing.Point(96, 16); this.dtpDateTimeFilterValue.Name = "dtpDateTimeFilterValue"; this.dtpDateTimeFilterValue.Size = new System.Drawing.Size(232, 20); this.dtpDateTimeFilterValue.TabIndex = 5; this.dtpDateTimeFilterValue.Visible = false; // // txtNumberFilterValue // this.txtNumberFilterValue.AutoScrollMargin = new System.Drawing.Size(0, 0); this.txtNumberFilterValue.AutoScrollMinSize = new System.Drawing.Size(0, 0); this.txtNumberFilterValue.Location = new System.Drawing.Point(96, 16); this.txtNumberFilterValue.Name = "txtNumberFilterValue"; this.txtNumberFilterValue.Size = new System.Drawing.Size(232, 20); this.txtNumberFilterValue.TabIndex = 3; this.txtNumberFilterValue.Text = "0"; this.txtNumberFilterValue.TextAlignment = Janus.Windows.GridEX.TextAlignment.Near; this.txtNumberFilterValue.ValueType = Janus.Windows.GridEX.NumericEditValueType.Int32; // // tbpMultiSelectList // this.tbpMultiSelectList.Controls.Add(this.grbMultiSelectList); this.tbpMultiSelectList.Location = new System.Drawing.Point(4, 22); this.tbpMultiSelectList.Name = "tbpMultiSelectList"; this.tbpMultiSelectList.Size = new System.Drawing.Size(336, 80); this.tbpMultiSelectList.TabIndex = 1; this.tbpMultiSelectList.Text = "Elegir de una Lista"; // // grbMultiSelectList // this.grbMultiSelectList.Controls.Add(this.label3); this.grbMultiSelectList.Controls.Add(this.multiSelectList); this.grbMultiSelectList.Location = new System.Drawing.Point(0, 0); this.grbMultiSelectList.Name = "grbMultiSelectList"; this.grbMultiSelectList.Size = new System.Drawing.Size(336, 80); this.grbMultiSelectList.TabIndex = 12; this.grbMultiSelectList.TabStop = false; // // label3 // this.label3.Location = new System.Drawing.Point(16, 17); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(80, 23); this.label3.TabIndex = 15; this.label3.Text = "Valores :"; // // multiSelectList // this.multiSelectList.Location = new System.Drawing.Point(96, 16); this.multiSelectList.MultipleItemsSelectedLegend = "[Varios]"; this.multiSelectList.Name = "multiSelectList"; this.multiSelectList.NoneItemsSelectedLegend = "[Ninguno]"; this.multiSelectList.Size = new System.Drawing.Size(232, 21); this.multiSelectList.TabIndex = 7; this.multiSelectList.OnBindRequired += new MultiSelectList.BindRequired(this.BindMultiSelectList); // // txtFilterCondition2 // this.txtFilterCondition2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtFilterCondition2.Location = new System.Drawing.Point(16, 296); this.txtFilterCondition2.Multiline = true; this.txtFilterCondition2.Name = "txtFilterCondition2"; this.txtFilterCondition2.ReadOnly = true; this.txtFilterCondition2.Size = new System.Drawing.Size(487, 56); this.txtFilterCondition2.TabIndex = 13; this.txtFilterCondition2.TabStop = false; this.txtFilterCondition2.Text = ""; // // btnCleanFilter // this.btnCleanFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnCleanFilter.Location = new System.Drawing.Point(368, 200); this.btnCleanFilter.Name = "btnCleanFilter"; this.btnCleanFilter.Size = new System.Drawing.Size(136, 30); this.btnCleanFilter.TabIndex = 12; this.btnCleanFilter.Text = "Quitar Todo"; this.btnCleanFilter.Click += new System.EventHandler(this.btnCleanFilter_Click); // // btnRemoveCondition // this.btnRemoveCondition.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnRemoveCondition.Location = new System.Drawing.Point(368, 160); this.btnRemoveCondition.Name = "btnRemoveCondition"; this.btnRemoveCondition.Size = new System.Drawing.Size(136, 30); this.btnRemoveCondition.TabIndex = 11; this.btnRemoveCondition.Text = "Quitar"; this.btnRemoveCondition.Click += new System.EventHandler(this.btnRemoveCondition_Click); // // btnAddCondition // this.btnAddCondition.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnAddCondition.Location = new System.Drawing.Point(368, 120); this.btnAddCondition.Name = "btnAddCondition"; this.btnAddCondition.Size = new System.Drawing.Size(136, 30); this.btnAddCondition.TabIndex = 9; this.btnAddCondition.Text = "Agregar"; this.btnAddCondition.Click += new System.EventHandler(this.btnAddCondition_Click); // // grbLogicalOperator // this.grbLogicalOperator.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.grbLogicalOperator.Controls.Add(this.rbtOr); this.grbLogicalOperator.Controls.Add(this.rbtAnd); this.grbLogicalOperator.Location = new System.Drawing.Point(368, 70); this.grbLogicalOperator.Name = "grbLogicalOperator"; this.grbLogicalOperator.Size = new System.Drawing.Size(136, 42); this.grbLogicalOperator.TabIndex = 8; this.grbLogicalOperator.TabStop = false; // // rbtOr // this.rbtOr.Location = new System.Drawing.Point(88, 16); this.rbtOr.Name = "rbtOr"; this.rbtOr.Size = new System.Drawing.Size(40, 16); this.rbtOr.TabIndex = 1; this.rbtOr.Text = "OR"; // // rbtAnd // this.rbtAnd.Checked = true; this.rbtAnd.Location = new System.Drawing.Point(8, 16); this.rbtAnd.Name = "rbtAnd"; this.rbtAnd.Size = new System.Drawing.Size(56, 16); this.rbtAnd.TabIndex = 0; this.rbtAnd.TabStop = true; this.rbtAnd.Text = "AND"; // // trvFilterCondition // this.trvFilterCondition.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trvFilterCondition.ImageIndex = -1; this.trvFilterCondition.Location = new System.Drawing.Point(16, 160); this.trvFilterCondition.Name = "trvFilterCondition"; this.trvFilterCondition.SelectedImageIndex = -1; this.trvFilterCondition.Size = new System.Drawing.Size(344, 128); this.trvFilterCondition.TabIndex = 10; // // cmbColumn // this.cmbColumn.Location = new System.Drawing.Point(120, 8); this.cmbColumn.Name = "cmbColumn"; this.cmbColumn.Size = new System.Drawing.Size(232, 21); this.cmbColumn.TabIndex = 0; this.cmbColumn.SelectedIndexChanged += new System.EventHandler(this.cmbColumn_SelectedIndexChanged); // // lblFilterColumn // this.lblFilterColumn.Location = new System.Drawing.Point(40, 8); this.lblFilterColumn.Name = "lblFilterColumn"; this.lblFilterColumn.Size = new System.Drawing.Size(72, 23); this.lblFilterColumn.TabIndex = 2; this.lblFilterColumn.Text = "Filtrar por :"; this.lblFilterColumn.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // btnAccept // this.btnAccept.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnAccept.Location = new System.Drawing.Point(8, 368); this.btnAccept.Name = "btnAccept"; this.btnAccept.TabIndex = 14; this.btnAccept.Text = "Aceptar"; this.btnAccept.Click += new System.EventHandler(this.btnAccept_Click); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(438, 368); this.btnCancel.Name = "btnCancel"; this.btnCancel.TabIndex = 15; this.btnCancel.Text = "Cancelar"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // GridFilterForm // this.AcceptButton = this.btnAccept; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(522, 399); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnAccept); this.Controls.Add(this.pnlMain); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "GridFilterForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Definir Filtro"; this.pnlMain.ResumeLayout(false); this.tbcCondition.ResumeLayout(false); this.tbpCondition.ResumeLayout(false); this.grbCondition.ResumeLayout(false); this.tbpMultiSelectList.ResumeLayout(false); this.grbMultiSelectList.ResumeLayout(false); this.grbLogicalOperator.ResumeLayout(false); this.ResumeLayout(false); }
public static HtmlString CheckBoxList(this IHtmlHelper htmlHelper, string name, MultiSelectList listInfos) { return(CheckBoxList(htmlHelper, name, listInfos, 0)); }
public ManagerData() { ManagerSelectList = new List <SelectListItem>(0); ManagerMultiSelectList = new MultiSelectList(ManagerSelectList, "Value", "Text"); }
public ModifyLecturerViewModel() { Groups = new MultiSelectList(new List <Correlation>(CorrelationService.GetCorrelation("Group", null)), "Id", "Name"); }
public static MvcHtmlString CheckBoxListFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty[]> > expression, MultiSelectList multiSelectList, object htmlAttributes = null) { //Derive property name for checkbox name var body = (MemberExpression)expression.Body; var propertyName = body.Member.Name; //Get currently select values from the ViewData model TProperty[] list = expression.Compile().Invoke(htmlHelper.ViewData.Model); //Convert selected value list to a List<string> for easy manipulation List <string> selectedValues = new List <string>(); if (list != null) { selectedValues = new List <TProperty>(list).ConvertAll(i => i.ToString()); } //Create div TagBuilder divTag = new TagBuilder("div"); divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true); //Add checkboxes foreach (SelectListItem item in multiSelectList) { divTag.InnerHtml += String.Format("<div><input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" " + "value=\"{1}\" {2} /><label for=\"{0}_{1}\">{3}</label></div>", propertyName, item.Value, selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "", item.Text); } return(MvcHtmlString.Create(divTag.ToString())); }
public void BindSelects(Patient patient) { List <SelectList> diagnosesTypes = new List <SelectList>(); List <SelectList> diagnosesCategories = new List <SelectList>(); List <SelectList> drugs = new List <SelectList>(); List <MultiSelectList> sideEffects = new List <MultiSelectList>(); List <SelectList> patientImmunoglobines = new List <SelectList>(); List <SelectList> radiologyTypes = new List <SelectList>(); List <SelectList> findings = new List <SelectList>(); List <SelectList> chestDistributions = new List <SelectList>(); List <SelectList> chestLocations = new List <SelectList>(); List <SelectList> grades = new List <SelectList>(); List <SelectList> treatmentResponses = new List <SelectList>(); List <SelectList> allergyItems = new List <SelectList>(); List <MultiSelectList> allergySideEffects = new List <MultiSelectList>(); for (int i = 0; i < patient.PatientDiagnoses.Count; i++) { var item = patient.PatientDiagnoses.ToList()[i]; diagnosesTypes.Add(DiagnosisTypeDropDownList(item.DiagnosisTypeId)); diagnosesCategories.Add(DiagnosisCategoriesDropDownList(item.DiagnosisCategoryId)); } for (int i = 0; i < patient.PatientDrugs.Count; i++) { var item = patient.PatientDrugs.ToList()[i]; drugs.Add(DrugsDropDownList(item.DrugId)); if (item.SideEffects.Any()) { MultiSelectList list = PopulateSideEffectsDropDownList(item.SelectedEffectsIds); sideEffects.Add(list); } else { MultiSelectList list = PopulateSideEffectsDropDownList(new List <int>()); sideEffects.Add(list); } } var igListSortedChronologically = patient.PatientImmunoglobulines. OrderByDescending(d => d.DateTaken). ToList(); for (int i = 0; i < igListSortedChronologically.Count; i++) { var item = igListSortedChronologically[i]; patientImmunoglobines.Add(ImmunoglobinTypesDropdownList(item.ImmunoglobulinTypeId)); } var radiologyListSortedChronologically = patient.PatientRadiologyFindings. OrderByDescending(d => d.DateTaken). ToList(); var allergyItemsList = patient.PatientAllergicIntoleranceItems.OrderByDescending(item => item.ID).ToList(); for (int i = 0; i < allergyItemsList.Count; i++) { var item = allergyItemsList[i]; if (item.SideEffects.Any()) { MultiSelectList list = PopulateSideEffectsDropDownList(item.SelectedEffectsIds); allergySideEffects.Add(list); } else { MultiSelectList list = PopulateSideEffectsDropDownList(new List <int>()); allergySideEffects.Add(list); } switch (item.AllergyIntoleranceItemType) { case "Drug": allergyItems.Add(DrugsDropDownList(item.AllergyIntoleranceItemId)); break; case "Food": allergyItems.Add(FoodsDropdownList(item.AllergyIntoleranceItemId)); break; case "Fungi": allergyItems.Add(FungiDropdownList(item.AllergyIntoleranceItemId)); break; case "Other": allergyItems.Add(OtherAllergicItemList(item.AllergyIntoleranceItemId)); break; } } for (int i = 0; i < radiologyListSortedChronologically.Count; i++) { var item = radiologyListSortedChronologically[i]; radiologyTypes.Add(PopulateRadiologyDropdownList("RadiologyType", item.RadiologyTypeId)); findings.Add(PopulateRadiologyDropdownList("Finding", item.FindingId)); chestLocations.Add(PopulateRadiologyDropdownList("ChestLocation", item.ChestLocationId)); chestDistributions.Add(PopulateRadiologyDropdownList("ChestDistribution", item.ChestDistributionId)); grades.Add(PopulateRadiologyDropdownList("Grade", item.GradeId)); treatmentResponses.Add(PopulateRadiologyDropdownList("TreatmentResponse", item.TreatmentResponseId)); } _viewBag.DiagnosisTypes = diagnosesTypes; _viewBag.DiagnosisCategories = diagnosesCategories; _viewBag.Drugs = drugs; _viewBag.SideEffects = sideEffects; _viewBag.ImmunoglobulinTypeId = patientImmunoglobines; _viewBag.RadiologyTypeId = radiologyTypes; _viewBag.FindingId = findings; _viewBag.ChestLocationId = chestLocations; _viewBag.ChestDistributionId = chestDistributions; _viewBag.GradeId = grades; _viewBag.TreatmentResponseId = treatmentResponses; _viewBag.ItemId = allergyItems; _viewBag.allergySideEffects = allergySideEffects; PopulatePatientStatusesDropdownList(patient.PatientStatusId); }
public async Task <IActionResult> Edit(int id, [Bind("RegattaId,RegattaName,RegattaVon,RegattaBis,Waterdepth,Startslots,ReportText,ReportSchedule,ReportOpening," + "ReportAddress,ReportTel,ReportFax,ReportMail,Judge,Awards,Security,ScheduleText,SubscriberFee,Accomodation,Comment,Catering,ClubId,WaterId,Organizer,Category,StartersLastYear,IsApproved")] RegattaVM regattaVM, IEnumerable <int> OldclassIds, IEnumerable <int> CompetitionIds, IEnumerable <int> StartingFeeIds, IEnumerable <int> CampingFeeIds) { if (id != regattaVM.RegattaId) { return(NotFound()); } Regatta regatta = _context.Regattas.FirstOrDefault(e => e.RegattaId == regattaVM.RegattaId); regatta.Name = regattaVM.RegattaName; regatta.FromDate = regattaVM.RegattaVon; regatta.ToDate = regattaVM.RegattaBis; regatta.Waterdepth = regattaVM.Waterdepth; regatta.Startslots = regattaVM.Startslots; regatta.ReportText = regattaVM.ReportText; regatta.ReportSchedule = regattaVM.ReportSchedule; regatta.ReportOpening = regattaVM.ReportOpening; regatta.ReportAddress = regattaVM.ReportAddress; regatta.ReportTel = regattaVM.ReportTel; regatta.ReportFax = regattaVM.ReportFax; regatta.ReportMail = regattaVM.ReportMail; regatta.Judge = regattaVM.Judge; regatta.Awards = regattaVM.Awards; regatta.Security = regattaVM.Security; regatta.ScheduleText = regattaVM.ScheduleText; regatta.SubscriberFee = regattaVM.SubscriberFee; regatta.Accomodation = regattaVM.Accomodation; regatta.Catering = regattaVM.Catering; regatta.Comment = regattaVM.Comment; regatta.ClubId = regattaVM.ClubId; regatta.WaterId = regattaVM.WaterId; regatta.Organizer = regattaVM.Organizer; regatta.StartersLastYear = regattaVM.StartersLastYear; regatta.Category = regattaVM.Category; regatta.IsApproved = regattaVM.IsApproved; IEnumerable <RegattaOldclass> roc = _context.RegattaOldclasses.Where(e => e.RegattaId == regattaVM.RegattaId); IEnumerable <RegattaCampingFee> rcf = _context.RegattaCampingFees.Where(e => e.RegattaId == regattaVM.RegattaId); IEnumerable <RegattaCompetition> rc = _context.RegattaCompetitions.Where(e => e.RegattaId == regattaVM.RegattaId); IEnumerable <RegattaStartingFee> rsf = _context.RegattaStartingFees.Where(e => e.RegattaId == regattaVM.RegattaId); foreach (var oc in OldclassIds) { if (roc.Where(e => e.OldclassId == oc && e.RegattaId == regattaVM.RegattaId).Count() == 0) { _context.Regattas.Include(e => e.RegattaOldclasses).FirstOrDefault(m => m.RegattaId == regattaVM.RegattaId).RegattaOldclasses.Add(new RegattaOldclass { RegattaId = regattaVM.RegattaId, OldclassId = oc }); } } foreach (var cf in CampingFeeIds) { if (rcf.Where(e => e.CampingFeeId == cf && e.RegattaId == regattaVM.RegattaId).Count() == 0) { _context.Regattas.Include(e => e.RegattaCampingFees).FirstOrDefault(m => m.RegattaId == regattaVM.RegattaId).RegattaCampingFees.Add(new RegattaCampingFee { RegattaId = regattaVM.RegattaId, CampingFeeId = cf }); } } foreach (var rcid in CompetitionIds) { if (rc.Where(e => e.CompetitionId == rcid && e.RegattaId == regattaVM.RegattaId).Count() == 0) { _context.Regattas.Include(e => e.RegattaCompetitions).FirstOrDefault(m => m.RegattaId == regattaVM.RegattaId).RegattaCompetitions.Add(new RegattaCompetition { RegattaId = regattaVM.RegattaId, CompetitionId = rcid }); } } foreach (var rsfid in StartingFeeIds) { if (rsf.Where(e => e.StartingFeeId == rsfid && e.RegattaId == regattaVM.RegattaId).Count() == 0) { _context.Regattas.Include(e => e.RegattaStartingFees).FirstOrDefault(m => m.RegattaId == regattaVM.RegattaId).RegattaStartingFees.Add(new RegattaStartingFee { RegattaId = regattaVM.RegattaId, StartingFeeId = rsfid }); } } _context.SaveChanges(); foreach (var oldoc in roc) { if (!OldclassIds.Contains(oldoc.OldclassId)) { regatta.RegattaOldclasses.Remove(oldoc); } } foreach (var oldcf in rcf) { if (!CampingFeeIds.Contains(oldcf.CampingFeeId)) { regatta.RegattaCampingFees.Remove(oldcf); } } foreach (var oldrcid in rc) { if (!CompetitionIds.Contains(oldrcid.CompetitionId)) { regatta.RegattaCompetitions.Remove(oldrcid); } } foreach (var oldrsfid in rsf) { if (!StartingFeeIds.Contains(oldrsfid.StartingFeeId)) { regatta.RegattaStartingFees.Remove(oldrsfid); } } if (ModelState.IsValid) { try { _context.Update(regatta); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RegattaExists(regatta.RegattaId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["ClubId"] = new SelectList(_context.Clubs, "ClubId", "ClubId", regatta.ClubId); ViewData["WaterId"] = new SelectList(_context.Waters, "WaterId", "WaterId", regatta.WaterId); ViewData["RegattaOldclasses"] = new MultiSelectList(_context.Oldclasses, "OldclassId", "Name", regattaVM.RegattaOldclasses.Select(e => e.OldclassId).ToList()); ViewData["RegattaCompetitions"] = new MultiSelectList(_context.Competitions, "CompetitionId", "Name", regattaVM.RegattaCompetitions.Select(e => e.CompetitionId).ToList()); ViewData["RegattaStartingFees"] = new MultiSelectList(_context.StartingFees, "StartingFeeId", "Name", regattaVM.RegattaStartingFees.Select(e => e.StartingFeeId).ToList()); ViewData["RegattaCampingFees"] = new MultiSelectList(_context.CampingFees, "CampingFeeId", "Name", regattaVM.RegattaCampingFees.Select(e => e.CampingFeeId).ToList()); return(View(regattaVM)); }
private void GetRelated() { // Clear related Properties.Clear(); if (Template != null) { // Get Properties foreach (string name in Template.Properties) { Property prp = Property.GetSingle("property_name = @0 AND property_parent_id = @1 AND property_draft = @2", name, Post.Id, Post.IsDraft); if (prp != null) { Properties.Add(prp); } else { Properties.Add(new Property() { Name = name, ParentId = Post.Id, IsDraft = Post.IsDraft }); } } } // Get selected categories if (PostCategories.Count > 0) { Categories = new MultiSelectList(Category.GetFields("category_id, category_name", new Params() { OrderBy = "category_name" }), "Id", "Name", PostCategories); } // Get attached content if (Post.Attachments.Count > 0) { // Content meta data is actually memcached, so this won't result in multiple queries Post.Attachments.ForEach(a => { Models.Content c = Models.Content.GetSingle(a, true); if (c != null) { AttachedContent.Add(c); } }); } // Get extensions Extensions = Post.GetExtensions(true); // Get whether comments should be enabled EnableComments = Areas.Manager.Models.CommentSettingsModel.Get().EnablePosts; if (!Post.IsNew && EnableComments) { using (var db = new DataContext()) { Comments = db.Comments. Include("CreatedBy"). Where(c => c.ParentId == Post.Id && c.ParentIsDraft == false). OrderByDescending(c => c.Created).ToList(); } } }
public ActionResult EmployeesList(FormCollection form) { using (DbContextModel db = new DbContextModel()) { var workersList = db.UserAccounts.Where(u => u.Role == Roles.Pracownik).ToList(); var skills = db.Skills.ToList(); MultiSelectList skillsList = new MultiSelectList(skills, "SkillId", "SkillName"); TempData["Skills"] = skillsList; foreach (var employee in workersList) { if (employee.Skills != null) { employee.SkillsArray = employee.Skills.Split(',').ToArray(); foreach (var skillId in employee.SkillsArray) { var skillIdInt = Convert.ToInt32(skillId); var skill = db.Skills.Where(x => x.SkillId.Equals(skillIdInt)).FirstOrDefault(); employee.SkillsCollection.Add(skill); } } } List <UserBasicModel> filteredDataContext = new List <UserBasicModel>(); string rateValue = form["rateValueText"]; string rateValuePreparedToDoubleConvert = rateValue.Replace(".", ","); double minimumAverageRate = 0; if (rateValue != "") { minimumAverageRate = Convert.ToDouble(rateValuePreparedToDoubleConvert); } if (form["Skills"] != null || form["rateValueText"] != null) { if (form["Skills"] != null) { var selectedSkills = form["Skills"]; var selectedSkillsArray = selectedSkills.Split(',').ToArray(); int countOfSelectedSkills = selectedSkillsArray.Count(); foreach (var employee in workersList) { bool flag = false; for (int i = 0; i < countOfSelectedSkills; i++) { if (employee.SkillsArray.Contains(selectedSkillsArray[i])) { flag = true; } else { flag = false; } } if (flag) { filteredDataContext.Add(employee); } } if (form["rateValueText"] != null) { var filteredDataContextWithCheckedAverageRateAndSkills = filteredDataContext.Where(x => x.AverageRate >= minimumAverageRate).ToList(); return(View(filteredDataContextWithCheckedAverageRateAndSkills)); } else { return(View(filteredDataContext)); } } else if (form["rateValueText"] != null) { var filteredDataContextWithCheckedAverageRate = workersList.Where(x => x.AverageRate >= minimumAverageRate).ToList(); return(View(filteredDataContextWithCheckedAverageRate)); } } return(View(workersList)); } }
private ProgramacionRuta GetProgramacionRuta(int?id, int idCliente, int idClienteDireccion, int idRuta) { var itemsTareasCatalog = new List <SelectListItem>(); if (id == null) { var model = new ProgramacionRuta(); ViewBag.ButtonLabel = Rp3.AgendaComercial.Resources.LabelFor.Agregar; ViewBag.DiarioDisplay = "block"; ViewBag.SemanalDisplay = "none"; ViewBag.MensualDisplay = "none"; ViewBag.MensualDiaDisplay = "block"; ViewBag.MensualElDisplay = "none"; model.TipoMensual = "1"; model.ConFechaFin = true; var tareas = DataBase.Tareas.GetSync(idRuta, null, null).Where(p => p.TipoTarea != Models.Constantes.TipoTarea.CheckListOportunidad && p.Estado == Models.Constantes.Estado.Activo); foreach (Tarea tar in tareas) { itemsTareasCatalog.Add(new SelectListItem() { Text = tar.Descripcion, Value = tar.IdTarea + "", Selected = true }); } var itemsTareas = new MultiSelectList(itemsTareasCatalog, "Value", "Text", itemsTareasCatalog.Select(p => p.Value).ToList()); ViewBag.ItemsTareas = itemsTareas; return(model); } else { var tareasProgramadas = DataBase.ProgramacionRutaTareas.Get(p => p.IdProgramacionRuta == id.Value).Select(p => p.IdTarea).ToList(); var tareas = DataBase.Tareas.GetSync(idRuta, null, null).Where(p => p.TipoTarea != Models.Constantes.TipoTarea.CheckListOportunidad); foreach (Tarea tar in tareas) { itemsTareasCatalog.Add(new SelectListItem() { Text = tar.Descripcion, Value = tar.IdTarea + "", Selected = tareasProgramadas.Contains(tar.IdTarea) }); } var itemsTareas = new MultiSelectList(itemsTareasCatalog, "Value", "Text", tareasProgramadas); ViewBag.ItemsTareas = itemsTareas; ViewBag.ButtonLabel = Rp3.AgendaComercial.Resources.LabelFor.Guardar; var model = DataBase.ProgramacionRutas.Get(p => p.IdProgramacionRuta == id).FirstOrDefault(); model.TipoMensual = "1"; ViewBag.MensualDiaDisplay = "block"; ViewBag.MensualElDisplay = "none"; if (model.Patron == "D") { ViewBag.DiarioDisplay = "block"; ViewBag.SemanalDisplay = "none"; ViewBag.MensualDisplay = "none"; } if (model.Patron == "S") { ViewBag.DiarioDisplay = "none"; ViewBag.SemanalDisplay = "block"; ViewBag.MensualDisplay = "none"; itemsDiasSemana = new List <SelectListItem> { new SelectListItem { Text = "Lunes", Value = "1", Selected = model.Lunes }, new SelectListItem { Text = "Martes", Value = "2", Selected = model.Martes }, new SelectListItem { Text = "Miércoles", Value = "3", Selected = model.Miercoles }, new SelectListItem { Text = "Jueves", Value = "4", Selected = model.Jueves }, new SelectListItem { Text = "Viernes", Value = "5", Selected = model.Viernes }, new SelectListItem { Text = "Sábado", Value = "6", Selected = model.Sabado }, new SelectListItem { Text = "Domingo", Value = "7", Selected = model.Domingo }, }; var selectedItems = itemsDiasSemana.Where(p => p.Selected == true).Select(p => p.Value).ToList(); //var listSelectedItems = new MultiSelectList(selectedItems, "Value", "Text"); var listDiasSemana = new MultiSelectList(itemsDiasSemana, "Value", "Text", selectedItems); ViewBag.ItemsDiasSemana = listDiasSemana; } if (model.Patron == "M") { ViewBag.DiarioDisplay = "none"; ViewBag.SemanalDisplay = "none"; ViewBag.MensualDisplay = "block"; if (model.Lunes || model.Martes || model.Miercoles || model.Jueves || model.Viernes || model.Sabado || model.Domingo || model.Dia || model.DiaLaboral || model.DiaFinDeSemana) { itemsDiasMensual = new List <SelectListItem> { new SelectListItem { Text = "Lunes", Value = "1", Selected = model.Lunes }, new SelectListItem { Text = "Martes", Value = "2", Selected = model.Martes }, new SelectListItem { Text = "Miércoles", Value = "3", Selected = model.Miercoles }, new SelectListItem { Text = "Jueves", Value = "4", Selected = model.Jueves }, new SelectListItem { Text = "Viernes", Value = "5", Selected = model.Viernes }, new SelectListItem { Text = "Sábado", Value = "6", Selected = model.Sabado }, new SelectListItem { Text = "Domingo", Value = "7", Selected = model.Domingo }, new SelectListItem { Text = "Día", Value = "8", Selected = model.Dia }, new SelectListItem { Text = "Día Laboral", Value = "9", Selected = model.DiaLaboral }, new SelectListItem { Text = "Fin de Semana", Value = "10", Selected = model.DiaFinDeSemana }, }; model.TipoMensual = "2"; ViewBag.ItemsDiasMensual = itemsDiasMensual; } } if (model.FechaFinTicks.HasValue && model.FechaFinTicks != 0) { model.ConFechaFin = true; } else { model.ConFechaFin = false; } return(model); } }
// GET: Players/Edit/5 public ActionResult Manage(Guid?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } // Retrieve Worker from db and perform null check //Worker worker = db.Workers.Find(id); var result = from s in db.SYSUsers join p in db.SYSUserProfiles on s.SYSUserID equals p.SYSUserID join t in db.UserTypes on p.UserTypeID equals t.ID where t.ID.Equals((int)UserType.w) select new Worker { ID = s.SYSUserID, //Guid.Parse("1"), //s.SYSUserID.ToString() FirstName = p.FirstName, LastName = p.LastName, Mobile = p.Mobile, Email = p.Email }; List <Worker> wlist = result.ToList(); Worker worker = wlist[0]; if (worker == null) { return(HttpNotFound()); } worker.WorkerId = (Guid)id; // Instantiate new instance of EditWorkerViewModel EditWorkerViewModel model = new EditWorkerViewModel { // Can set the Worker name and Id filds of the ViewModel WorkerId = worker.WorkerId.ToString(), Name = worker.FirstName }; // Retrieve list of worker jobs from db in order to find the teams that the Worker belongs to // var workerJobs = db.Jobs.Where(i => i.Workers.Any(j => j.WorkerId.Equals(worker.WorkerId))).ToList(); var qworkerJobs = from s in db.SYSUsers join p in db.SYSUserProfiles on s.SYSUserID equals p.SYSUserID join t in db.UserTypes on p.UserTypeID equals t.ID join j in db.JOBs on s.SYSUserID equals j.WorkerID //where j.WorkerID.Equals(1) select new Job { JobId = Guid.NewGuid() }; var jlist = qworkerJobs.ToList(); List <Job> workerJobs = jlist; //var WorkerJobs = db.Jobs.Where(t => t.Workers.Contains(new Worker { WorkerId = worker.WorkerId })).ToList(); // Check that workerJobs is not empty if (workerJobs != null) { // Initialize the array to number of teams in workerTeams string[] workerJobsIds = new string[workerJobs.Count()]; // Then, set the value of platerTeams.Count so the for loop doesn't need to work it out every iteration int length = workerJobs.Count(); // Now loop over each of the workerJobs and store the Id in the workerJobsId array for (int i = 0; i < length; i++) { // Note that we employ the ToString() method to convert the Guid to the string // workerJobs[i].JobId = new Guid(string.Format("00000000-0000-0000-0000-00{0:0000000000}", workerJobs[i].ID)); //Guid.Parse(workerJobs[i].ID.ToString()); workerJobsIds[i] = workerJobs[i].JobId.ToString(); } // Instantiate the MultiSelectList, plugging in our playerTeamIds array MultiSelectList jobsList = new MultiSelectList(db.JOBs.ToList().OrderBy(i => i.Description), "ID", "Description", workerJobsIds); // Now add the teamsList to the Teams property of our EditPlayerViewModel (model) model.Jobs = jobsList; model.JobIds = workerJobsIds.ToList(); // Return the ViewModel return(View(model)); } else { // Else instantiate the teamsList without any pre-selected values MultiSelectList jobsList = new MultiSelectList(db.JOBs.ToList().OrderBy(i => i.Description), "JobId", "Name"); // Set the Teams property of the EditWorkerViewModel with the teamsList model.Jobs = jobsList; // Return the ViewModel return(View(model)); } }
// public static IList<string> ToList(this string value, params char[] delimiters) // { // if (delimiters == null || delimiters.Length == 0) // throw new ArgumentException("You must provide as least one delimiter", "delimiters"); // List<string> list = new List<string>(); // if (!string.IsNullOrEmpty(value)) // { // string[] strArray = Enumerable.ToArray<string>(Enumerable.Select<string, string>((IEnumerable<string>)value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries), (Func<string, string>)(s => s.Trim()))); // if (strArray != null) // list.AddRange((IEnumerable<string>)strArray); // } // return (IList<string>)list.AsReadOnly(); // } public static MvcHtmlString CheckBoxListFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty[]> > expression, MultiSelectList multiSelectList, object htmlAttributes = null) { //Derive property name for checkbox name MemberExpression body = expression.Body as MemberExpression; string propertyName = body.Member.Name; //Get currently select values from the ViewData model TProperty[] list = expression.Compile().Invoke(htmlHelper.ViewData.Model); //Convert selected value list to a List<string> for easy manipulation List <string> selectedValues = new List <string>(); if (list != null) { selectedValues = new List <TProperty>(list).ConvertAll <string>(delegate(TProperty i) { return(i.ToString()); }); } //Create div TagBuilder divTag = new TagBuilder("div"); divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true); //Add checkboxes foreach (SelectListItem item in multiSelectList) { divTag.InnerHtml += String.Format("<div style='width:75px;float:left;'><input style='float:left;' type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" " + "value=\"{1}\" {2} /><label style='float:left; width:95px;padding-top:5px;padding-left:20px;' for=\"{0}_{1}\">{3}</label></div>", propertyName.Trim(), item.Value.Trim(), selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "", item.Text.Trim()); } return(MvcHtmlString.Create(divTag.ToString())); }
public virtual async Task <ActionResult> AddProduct(AddProductViewModel productModel) { if (!ModelState.IsValid) { ViewData["CategoriesSelectList"] = new MultiSelectList( (await _categoryService.GetAll()) .Union(productModel.Categories.Select(x => new Category { Name = x }), new ProductCategoryComparer()), "Name", "Name", productModel.Categories); return(View(productModel)); } if (productModel.Count <= 0) { productModel.Count = 0; productModel.ProductStatus = ProductStatus.NotAvailable;; } var addedProductImages = productModel.Images .Where(image => image.Id == null) .Select(image => new { image.Url, image.Name, image.ThumbnailUrl }) .ToList(); var deletedProductImages = new List <ProductImage>(); var product = new DomainClasses.Product(); foreach (var productImage in productModel.Images.Where(image => image.Id == null)) { productImage.Url = Url.Content("~/UploadedFiles/ProductImages/" + Path.GetFileName(getFilePath(productImage.Name, Server.MapPath("~/UploadedFiles/ProductImages")))); productImage.ThumbnailUrl = Url.Content("~/UploadedFiles/ProductImages/Thumbs/" + Path.GetFileName(getFilePath(productImage.Name, Server.MapPath("~/UploadedFiles/ProductImages/Thumbs")))); productImage.DeleteUrl = ""; } _mappingEngine.Map(productModel, product); if (productModel.Id.HasValue) { deletedProductImages = (await _productService.EditProduct(product)).ToList(); TempData["message"] = "کالای مورد نظر با موفقیت ویرایش شد"; } else { product.Title = productModel.Name; product.PostedDate = DateTime.Now; product.PostedByUserId = 1; await _productService.AddProduct(product); TempData["message"] = "کالای جدید با موفقیت ثبت شد"; } await _unitOfWork.SaveAllChangesAsync(); foreach (var productImage in addedProductImages) { var path = getFilePath(productImage.Name, Server.MapPath("~/UploadedFiles/ProductImages")); var thumbPath = getFilePath(productImage.Name, Server.MapPath("~/UploadedFiles/ProductImages/Thumbs")); System.IO.File.Move(Server.MapPath("~/Content/tmp/" + Path.GetFileName(productImage.Url)), path); System.IO.File.Move(Server.MapPath("~/Content/tmp/" + Path.GetFileName(productImage.ThumbnailUrl)), thumbPath); } foreach (var productImage in deletedProductImages) { var path = Server.MapPath("~/UploadedFiles/ProductImages/" + productImage.Name); var thumbPath = Server.MapPath("~/UploadedFiles/ProductImages/Thumbs/" + productImage.Name); System.IO.File.Delete(path); System.IO.File.Delete(thumbPath); } if (productModel.Id.HasValue) { LuceneIndex.ClearLuceneIndexRecord(productModel.Id.Value); } //Index the new product lucene.NET LuceneIndex.AddUpdateLuceneIndex(new LuceneSearchModel { ProductId = product.Id, Description = product.Body.RemoveHtmlTags(), Title = product.Title, ProductStatus = product.ProductStatus.ToString(), Price = product.Prices .OrderByDescending(productPrice => productPrice.Date) .Select(productPrice => productPrice.Price). FirstOrDefault(). ToString(CultureInfo.InvariantCulture), Image = product.Images.OrderBy(image => image.Order) .Select(image => image.ThumbnailUrl) .FirstOrDefault(), SlugUrl = product.SlugUrl, Category = "کالاها" }); return(RedirectToAction(MVC.Product.Admin.ActionNames.Index)); }
// GET: Cajas public async Task <IActionResult> Index(int?pg, int?rpp, string srt, bool?asc, string val) { if (pg == null) { pg = 1; } if (rpp == null) { rpp = 20; } if (string.IsNullOrEmpty(srt)) { srt = "Id"; } if (asc == null) { asc = true; } bool _asc = asc.Value; var pre = _context.Pago.Pre(val); var sort = _context.Pago.FilterSort(srt); ViewData = _context.Pago.ViewData(pre, pg, rpp, srt, asc, val); var Filters = ViewData["Filters"] as IDictionary <string, List <string> >; var applicationDbContext = _asc ? pre .OrderBy(x => sort.GetValue(x)) .Skip((pg.Value - 1) * rpp.Value).Take(rpp.Value) .Include(c => c.ApplicationUser) .Include(c => c.Vales) .Include(c => c.Oficina) .Include(p => p.Cliente) : pre .OrderByDescending(x => sort.GetValue(x)) .Skip((pg.Value - 1) * rpp.Value).Take(rpp.Value) .Include(c => c.ApplicationUser) .Include(c => c.Vales) .Include(c => c.Oficina) .Include(p => p.Cliente); ViewData[nameof(Medio)] = Medio.Cheque.Enum2Select(Filters); var clientSelect = new List <SelectListItem> { }; foreach (var c in _context.Pago.Select(v => v.ClienteId)) { var cliente = await _context.Cliente.SingleOrDefaultAsync(i => i.Id == c); var item = new SelectListItem { Value = c.ToString(), Text = string.Join(" / ", cliente.NoCliente, cliente.Name, string.Format(new InterceptProvider(), "{0:U}", c)) }; clientSelect.Add(item); } ViewData["ClienteId"] = new MultiSelectList(clientSelect, "Value", "Text"); //ViewData["ClienteId"] = new MultiSelectList( // from Cliente c in _context.Pago.Select(v => v.Cliente) // .GroupBy(c => c.Id).Select(c => c.First()) // select new // { // c.Id, // Name = String.Join(" / ", // c.NoCliente, c.Name, // String.Format(new InterceptProvider(), "{0:U}", c.Id)) // }, // "Id", "Name", Filters.ContainsKey("ClienteId") ? // Filters["ClienteId"] : null); var oficinaSelect = new List <SelectListItem> { }; foreach (var o in _context.Pago.Select(v => v.OficinaId).Distinct()) { var oficina = await _context.Oficina.SingleOrDefaultAsync(i => i.Id == o); var item = new SelectListItem { Value = o.ToString(), Text = oficina.Name }; oficinaSelect.Add(item); } ViewData["OficinaId"] = new MultiSelectList(oficinaSelect, "Value", "Text"); ViewData["ApplicationUserId"] = new MultiSelectList( from ApplicationUser c in _context.Pago .Select(v => v.ApplicationUser).GroupBy(c => c.Id) .Select(c => c.First()) select new { c.Id, Name = c.UserName }, "Id", "Name", Filters.ContainsKey("ApplicationUserId") ? Filters["ApplicationUserId"] : null); ViewData["Date"] = string.Format("'{0}'", string.Join("','", _context.Pago.Select(v => v.Date.Date .ToString("yyyy-M-d")).Distinct().ToList())); return(View(await applicationDbContext.ToListAsync())); }
public IActionResult Create([Bind("RegattaName,RegattaVon,RegattaBis,Waterdepth,Startslots,ReportText,ReportSchedule,ReportOpening," + "ReportAddress,ReportTel,ReportFax,ReportMail,Judge,Awards,Security,ScheduleText,SubscriberFee,Accomodation,Comment,Catering,ClubId,WaterId,Organizer,IsApproved")] RegattaVM regattaVM, IEnumerable <int> schueler, IEnumerable <int> jugend, IEnumerable <int> altersklassen, IEnumerable <int> alleklassen, IEnumerable <int> CompetitionIds, IEnumerable <int> StartingFeeIds, IEnumerable <int> CampingFeeIds) { Regatta regatta = new Regatta(); regatta.Name = regattaVM.RegattaName; regatta.FromDate = regattaVM.RegattaVon; regatta.ToDate = regattaVM.RegattaBis; regatta.Waterdepth = regattaVM.Waterdepth; regatta.Startslots = regattaVM.Startslots; regatta.ReportText = regattaVM.ReportText; regatta.ReportSchedule = regattaVM.ReportSchedule; regatta.ReportOpening = regattaVM.ReportOpening; regatta.ReportAddress = regattaVM.ReportAddress; regatta.ReportTel = regattaVM.ReportTel; regatta.ReportFax = regattaVM.ReportFax; regatta.ReportMail = regattaVM.ReportMail; regatta.Judge = regattaVM.Judge; regatta.Awards = regattaVM.Awards; regatta.Security = regattaVM.Security; regatta.ScheduleText = regattaVM.ScheduleText; regatta.SubscriberFee = regattaVM.SubscriberFee; regatta.Accomodation = regattaVM.Accomodation; regatta.Comment = regattaVM.Comment; regatta.Catering = regattaVM.Catering; regatta.ClubId = regattaVM.ClubId; regatta.WaterId = regattaVM.WaterId; regatta.Organizer = regattaVM.Organizer; regatta.StartersLastYear = regattaVM.StartersLastYear; regatta.Category = regattaVM.Category; regatta.IsApproved = regattaVM.IsApproved; if (ModelState.IsValid) { _context.Add(regatta); _context.SaveChanges(); foreach (var oc in schueler) { _context.RegattaOldclasses.Add(new RegattaOldclass { RegattaId = regatta.RegattaId, OldclassId = oc }); } foreach (var oc in jugend) { _context.RegattaOldclasses.Add(new RegattaOldclass { RegattaId = regatta.RegattaId, OldclassId = oc }); } foreach (var oc in altersklassen) { _context.RegattaOldclasses.Add(new RegattaOldclass { RegattaId = regatta.RegattaId, OldclassId = oc }); } foreach (var oc in alleklassen) { _context.RegattaOldclasses.Add(new RegattaOldclass { RegattaId = regatta.RegattaId, OldclassId = oc }); } foreach (var cf in CampingFeeIds) { _context.RegattaCampingFees.Add(new RegattaCampingFee { RegattaId = regatta.RegattaId, CampingFeeId = cf }); } foreach (var rcid in CompetitionIds) { _context.RegattaCompetitions.Add(new RegattaCompetition { RegattaId = regatta.RegattaId, CompetitionId = rcid }); } foreach (var rsfid in StartingFeeIds) { _context.RegattaStartingFees.Add(new RegattaStartingFee { RegattaId = regatta.RegattaId, StartingFeeId = rsfid }); } _context.SaveChanges(); return(RedirectToAction(nameof(Index))); } ViewData["ClubId"] = new SelectList(_context.Clubs, "ClubId", "Name", regatta.ClubId); ViewData["WaterId"] = new SelectList(_context.Waters, "WaterId", "Name", regatta.WaterId); ViewData["OldclassIds"] = new MultiSelectList(_context.Oldclasses, "OldclassId", "Name"); ViewData["CompetitionIds"] = new MultiSelectList(_context.Competitions.Include(e => e.Boatclasses).Include(e => e.Raceclasses), "CompetitionId", "Name"); ViewData["StartingFeeIds"] = new MultiSelectList(_context.StartingFees, "StartingFeeId", "Name"); ViewData["CampingFeeIds"] = new MultiSelectList(_context.CampingFees, "CampingFeeId", "LongName"); return(View(regattaVM)); }
//GET: Societies/Create public IActionResult Create() { ViewData["LessonId"] = new MultiSelectList(_lessonLogic.Read(null), "Id", "LessonName"); return(View()); }
// GET: Book/Create public IActionResult Create() { ViewData["genreId"] = new SelectList(_context.genres, "id", "name"); ViewData["authors"] = new MultiSelectList(_context.authors, "id", "fullName"); return(View()); }
public void SetSelectList(MultiSelectList selectList) { _selectList = selectList; }
// GET: Arqueos public IActionResult Index(int?pg, int?rpp, string srt, bool?asc, string val) { if (pg == null) { pg = 1; } if (rpp == null) { rpp = 20; } if (String.IsNullOrEmpty(srt)) { srt = "Date"; } if (asc == null) { asc = false; } bool _asc = asc.Value; var pre = _context.Arqueo.Pre(val); var sort = _context.Arqueo.FilterSort(srt); ViewData = _context.Arqueo.ViewData(pre, pg, rpp, srt, asc, val); var Filters = ViewData["Filters"] as IDictionary <string, List <string> >; var arqueos = _asc ? pre .OrderBy(x => sort.GetValue(x)) .Skip((pg.Value - 1) * rpp.Value).Take(rpp.Value) .Include(c => c.ApplicationUser) : pre .OrderByDescending(x => sort.GetValue(x)) .Skip((pg.Value - 1) * rpp.Value).Take(rpp.Value) .Include(c => c.ApplicationUser); var model = from Arqueo g in arqueos select new ArqueoVM { OficinaId = g.OficinaId, OfficeName = g.Oficina.Name, ApplicationUserId = g.ApplicationUserId, ApplicationUserName = g.ApplicationUser.UserName, Fecha = g.Date.Date, PagosEfectivo = _context.Pago.Where(p => p.Date.Date == g.Date.Date && p.Medio == Medio.Efectivo && p.OficinaId == g.OficinaId).Select(p => p.Monto).Sum(), PagosCheque = _context.Pago.Where(p => p.Date.Date == g.Date.Date && p.Medio == Medio.Cheque && p.OficinaId == g.OficinaId).Select(p => p.Monto).Sum(), PagosTransferencia = _context.Pago.Where(p => p.Date.Date == g.Date.Date && p.Medio == Medio.Transferencia && p.OficinaId == g.OficinaId).Select(p => p.Monto).Sum(), PagosTotal = _context.Pago.Where(p => p.Date.Date == g.Date.Date && p.OficinaId == g.OficinaId).Select(p => p.Monto).Sum(), RetiroEfectivo = _context.Retiro.Where(p => p.Date.Date == g.Date.Date && p.Forma == Forma.Efectivo && p.OficinaId == g.OficinaId).Select(p => p.Monto).Sum(), RetiroCheque = _context.Retiro.Where(p => p.Date.Date == g.Date.Date && p.Forma == Forma.Cheque && p.OficinaId == g.OficinaId).Select(p => p.Monto).Sum(), RetiroTotal = _context.Retiro.Where(p => p.Date.Date == g.Date.Date && p.OficinaId == g.OficinaId).Select(p => p.Monto).Sum(), SaldoAnterior = _context.Arqueo.Where(a => a.Date < g.Date.Date && a.OficinaId == g.OficinaId).OrderByDescending(t => t.Date).FirstOrDefault().Saldo, ArqueoCheques = g.Cheque, ArqueoEfectivo = g.Efectivo, ArqueoTransferencias = g.Transferencia, ArqueoTotal = g.ResultadoEjercicio }; foreach (ArqueoVM m in model as List <ArqueoVM> ) { m.DiferenciaEfectivo = m.ArqueoEfectivo - (m.SaldoAnterior + m.PagosEfectivo - m.RetiroEfectivo); m.DiferenciaCheques = m.ArqueoCheques - (m.PagosCheque - m.RetiroCheque); m.DiferenciaTransferencias = m.ArqueoTransferencias - m.PagosTransferencia; m.DiferenciaTotal = m.DiferenciaEfectivo + m.DiferenciaCheques + m.DiferenciaTransferencias; } var contextUser = _context.ApplicationUser .Include(u => u.PuestosTrabajo) .ThenInclude(p => p.Oficina) .SingleOrDefault(u => u.UserName == User.Identity.Name); ViewData["Oficinas"] = contextUser.PuestosTrabajo.Select(o => o.Oficina.Name).ToList(); ViewData["ApplicationUserId"] = new MultiSelectList( from ApplicationUser c in _context.Arqueo .Select(v => v.ApplicationUser).GroupBy(c => c.Id) .Select(c => c.First()) select new { c.Id, Name = c.UserName }, "Id", "Name", Filters.ContainsKey("ApplicationUserId") ? Filters["ApplicationUserId"] : null); ViewData["Date"] = String.Format("'{0}'", String.Join("','", _context.Arqueo.Select(v => v.Date.Date .ToString("yyyy-M-d")).Distinct().ToList())); return(View(model)); }
public new void SetSelectList <TKey, TValue>(IEnumerable <KeyValuePair <TKey, TValue> > list) { var selectList = new MultiSelectList(list, "Key", "Value"); _selectList = selectList; }
public ActionResult SearchProjectsWithFiltersCompleted(ProjectModel project) { using (DbContextModel db = new DbContextModel()) { var dataContext = db.Projects .Include("ProjectOwner") .Include("SkillsRequiredToProjectCollection") .Include("ProjectCategory") .OrderByDescending(x => x.ProjectCreationDate) .ToList(); var skills = db.Skills.ToList(); MultiSelectList skillsList = new MultiSelectList(skills, "SkillId", "SkillName"); TempData["Skills"] = skillsList; var categories = db.Categories.ToList(); MultiSelectList categoriesList = new MultiSelectList(categories, "CategoryId", "CategoryName"); TempData["Categories"] = categoriesList; foreach (var projectSearched in dataContext) { var projectCategoryId = projectSearched.ProjectCategory.CategoryId; projectSearched.ProjectCategory = categories.Where(x => x.CategoryId.Equals(projectCategoryId)).FirstOrDefault(); if (projectSearched.SkillsRequiredToProject != null) { projectSearched.SkillsRequiredToProjectArray = projectSearched.SkillsRequiredToProject.Split(',').ToArray(); foreach (var skillId in projectSearched.SkillsRequiredToProjectArray) { var skillIdInt = Convert.ToInt32(skillId); var skill = db.Skills.Where(x => x.SkillId.Equals(skillIdInt)).FirstOrDefault(); projectSearched.SkillsRequiredToProjectCollection.Add(skill); } } } if (project.SkillsRequiredToProjectArray != null || project.CategoriesToProjectArray != null) { IEnumerable <ProjectModel> filteredDataContext = new List <ProjectModel>(); if (project.SkillsRequiredToProjectArray != null) { filteredDataContext = from p in dataContext where project.SkillsRequiredToProjectArray.Any(val => p.SkillsRequiredToProject.Contains(val)) select p; } if (project.CategoriesToProjectArray != null) { IEnumerable <ProjectModel> filteredDataContextWithCategories = new List <ProjectModel>(); if (project.SkillsRequiredToProjectArray == null) { filteredDataContextWithCategories = dataContext.Where(x => project.CategoriesToProjectArray.Contains(x.ProjectCategory.CategoryId.ToString())).ToList(); } else { filteredDataContextWithCategories = filteredDataContext.Where(x => project.CategoriesToProjectArray.Contains(x.ProjectCategory.CategoryId.ToString())).ToList(); } return(View("SearchProjects", filteredDataContextWithCategories)); } return(View("SearchProjects", filteredDataContext)); } return(View("SearchProjects", dataContext)); } }
// GET: Cities/Create public IActionResult Create() { ViewData["GroupName"] = new MultiSelectList(_context.Groups, "GroupId", "Name"); return(View()); }
public async Task <IActionResult> Create([Bind("Id,Title,Content,Summary," + "PublishedDateTime,Url,VisitorCount,CreatedAt,ModifiedAt,BlogId," + "AuthorId,CategoryId,TagIds")] Post post, IFormFile headerImage) { if (ModelState.IsValid) { Models.File file = null; if (headerImage == null || (headerImage != null && !headerImage.ContentType.ToLower().StartsWith("image/"))) { await _postRepository.ExecuteAsync( new CreatePostCommand(_context) { Title = post.Title, Summary = post.Summary, Content = post.Content, PublishedDateTime = post.PublishedDateTime, AuthorId = post.AuthorId, BlogId = post.BlogId, CategoryId = post.CategoryId, TagIds = post.TagIds }); return(RedirectToAction("Index")); } MemoryStream ms = new MemoryStream(); headerImage.OpenReadStream().CopyTo(ms); file = new Models.File() { Id = Guid.NewGuid(), Name = headerImage.Name, FileName = Path.GetFileName(headerImage.FileName), Content = ms.ToArray(), Length = headerImage.Length, ContentType = headerImage.ContentType }; var transactions = new TransactionScope(); try { if (file != null) { transactions.Transactions.Add(_filesContext.Database.BeginTransaction()); await _fileRepository.ExecuteAsync( new CreateFileCommand(_filesContext) { Content = file.Content, ContentDisposition = file.ContentDisposition, ContentType = file.ContentType, FileName = file.FileName, Id = file.Id, Length = file.Length, Name = file.Name }); } transactions.Transactions.Add(_context.Database.BeginTransaction()); await _postRepository.ExecuteAsync( new CreatePostCommand(_context) { Title = post.Title, Summary = post.Summary, Content = post.Content, PublishedDateTime = post.PublishedDateTime, AuthorId = post.AuthorId, BlogId = post.BlogId, CategoryId = post.CategoryId, TagIds = post.TagIds, FileId = file.Id }); transactions.Commit(); } catch (Exception exception) { transactions.Rollback(); ExceptionDispatchInfo.Capture(exception.InnerException).Throw(); } return(RedirectToAction("Index")); } ViewData["AuthorId"] = new SelectList(_context.Users, "Id", "Id", post.AuthorId); ViewData["BlogId"] = new SelectList(_context.Blogs, "Id", "Url", post.BlogId); ViewData["CategoryId"] = new SelectList(_context.Set <Category>(), "Id", "Id", post.CategoryId); ViewData["TagIds"] = new MultiSelectList(_context.Tags, "Id", "Name", post.TagIds); return(View(post)); }
public async Task <IActionResult> Index(string searchTerm, int?department, int?category, int?topicTypeId, string number, int?pageIndex, int?year, DateTime?fromDate, DateTime?toDate, int[] authorids) { // Pagging and Searching ViewBag.SearchTerm = searchTerm; ViewBag.Depertment = department; ViewBag.Category = category; ViewBag.TopicType = topicTypeId; ViewBag.Number = number; ViewBag.Year = year; ViewBag.FromDate = fromDate; ViewBag.ToDate = toDate; ViewBag.Departments = await _context.Departments.Take(10).Select(x => new DepartmentSearchModel() { DepartmentId = x.DepartmentId, Name = x.Name, Count = _context.Topics.Count(c => c.DepartmentId == x.DepartmentId) }).ToListAsync(); ViewBag.TopicTypes = await _context.TopicTypes.Take(10).Select(x => new TopicTypeSearchModel() { TopicTypeId = x.TopicTypeId, Name = x.Name, Count = _context.Topics.Count(c => c.TopicTypeId == x.TopicTypeId) }).ToListAsync(); ViewBag.CategoriesSelect = new SelectList(_context.Categories, "CategoryId", "Name", category); ViewBag.DepartmentsSelect = new SelectList(_context.Departments, "DepartmentId", "Name", department); ViewBag.TopicTypesSelect = new SelectList(_context.TopicTypes, "TopicTypeId", "Name", topicTypeId); ViewBag.Years = new SelectList(_context.Topics.Where(x => x.PublishDate != null).Select(x => x.PublishDate.Value.Year).Distinct(), year); ViewData["Authors"] = new MultiSelectList(_context.Authors, "AuthorId", "Name", authorids); var topics = _context.Topics.AsQueryable(); if (!string.IsNullOrEmpty(searchTerm)) { topics = topics.Where(x => x.Name.Contains(searchTerm) || x.Description.Contains(searchTerm) || x.Content.Contains(searchTerm)); } if (department != null) { topics = topics.Where(x => x.DepartmentId == department); } if (category != null) { topics = topics.Where(x => x.CategoryId == category); } if (!string.IsNullOrEmpty(number)) { topics = topics.Where(x => x.Number.Contains(number)); } if (topicTypeId != null) { topics = topics.Where(x => x.TopicTypeId == topicTypeId); } if (year != null) { topics = topics.Where(x => x.PublishDate != null && x.PublishDate.Value.Year == year); } if (fromDate != null && toDate != null) { topics = topics.Where(x => x.PublishDate >= fromDate && x.PublishDate <= toDate); } if (authorids?.Length > 0) { topics = topics.Where(x => x.AuthorTopics.Any(x => authorids.Contains(x.AuthorId))); } return(View(await PaginatedList <Topic> .CreateAsync(topics.OrderByDescending(x => x.ModifiedDate), pageIndex ?? 1, 10))); }
public ActionResult Settings() { ViewData["lstUnitFilter"] = new MultiSelectList((from u in this.db.Units select u), "Id", "DisplayName", this.UserSettings.UnitFilter); ViewData["coordDisplay"] = (int)this.UserSettings.CoordinateDisplay; return(View()); }
// GET: Players/Edit/5 public ActionResult Edit(Guid?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } // Retrieve Player from db and perform null check Player player = db.Players.Find(id); if (player == null) { return(HttpNotFound()); } // Instantiate new instance of EditPlayerViewModel EditPlayerViewModel model = new EditPlayerViewModel { // Can set the player name and Id filds of the ViewModel PlayerId = player.PlayerId.ToString(), Name = player.Name }; // Retrieve list of player teams from db in order to find the teams that the player belongs to var playerTeams = db.Teams.Where(i => i.Players.Any(j => j.PlayerId.Equals(player.PlayerId))).ToList(); //var playerTeams = db.Teams.Where(t => t.Players.Contains(new Player { PlayerId = player.PlayerId })).ToList(); // Check that playerTeams is not empty if (playerTeams != null) { // Initialize the array to number of teams in playerTeams string[] playerTeamsIds = new string[playerTeams.Count]; // Then, set the value of platerTeams.Count so the for loop doesn't need to work it out every iteration int length = playerTeams.Count; // Now loop over each of the playerTeams and store the Id in the playerTeamsId array for (int i = 0; i < length; i++) { // Note that we employ the ToString() method to convert the Guid to the string playerTeamsIds[i] = playerTeams[i].TeamId.ToString(); } // Instantiate the MultiSelectList, plugging in our playerTeamIds array MultiSelectList teamsList = new MultiSelectList(db.Teams.ToList().OrderBy(i => i.Name), "TeamId", "Name", playerTeamsIds); // Now add the teamsList to the Teams property of our EditPlayerViewModel (model) model.Teams = teamsList; // Return the ViewModel return(View(model)); } else { // Else instantiate the teamsList without any pre-selected values MultiSelectList teamsList = new MultiSelectList(db.Teams.ToList().OrderBy(i => i.Name), "TeamId", "Name"); // Set the Teams property of the EditPlayerViewModel with the teamsList model.Teams = teamsList; // Return the ViewModel return(View(model)); } }
public async Task <ActionResult> EditActiveDirectoryUser(UserDetail userDetail) { if (ModelState.IsValid) { ViewBag.SystemAdmin = false; var identity = (System.Security.Claims.ClaimsIdentity)User.Identity; var claims = identity.Claims; string SystemAdmin = claims.FirstOrDefault(x => x.Type == "SystemAdmin")?.Value; if (SystemAdmin == "True") { ViewBag.SystemAdmin = true; } var token = GetToken(); userDetail.Roles = new List <RoleDetail>(); if (userDetail.RoleIds == null) { var message = "Must select at least one role for user."; throw new InvalidOperationException(message); } if (userDetail.RoleIds.Count > 0) { var userRoles = new List <RoleDetail>(); foreach (var id in userDetail.RoleIds) { var roles = await IzendaUtilities.GetRoles(token); var roleId = roles.FirstOrDefault(i => i.Id == Guid.Parse(id)).Id.ToString(); var role = roles.Where(i => i.Id == Guid.Parse(roleId)).Select(v => new RoleDetail { Id = v.Id, Name = v.Name }).FirstOrDefault(); if (roleId != null) { try { userDetail.Roles.Add(role); userRoles.Add(role); } catch (Exception e) { Console.WriteLine(e); throw; } } } var allRoles = await IzendaUtilities.GetRoles(token); var rolesToRemove = allRoles.Except(userRoles); foreach (var role in rolesToRemove) { try { userDetail.Roles.Remove(role); } catch (Exception e) { Console.WriteLine(e); throw; } } } try { var success = false; var izendaUsers = new List <UserDetail>(); izendaUsers = await IzendaUtilities.IzendaGetAllUsers(token); var currentUser = izendaUsers.FirstOrDefault(x => x.EmailAddress == userDetail.EmailAddress); if (currentUser == null) { success = await IzendaUtilities.SaveIzendaUser(token, userDetail); if (success) { var combinedList = CacheSystem.GetCacheItem("combinedList") as List <UserDetail>; var duplicateUserDetail = combinedList.FirstOrDefault(e => e.EmailAddress == userDetail.EmailAddress); combinedList.Remove(duplicateUserDetail); combinedList.Add(userDetail); return(PartialView("ActiveDirectoryList", combinedList)); } } if (currentUser != null && currentUser.Active != userDetail.Active) { if (currentUser.Active && !userDetail.Active) { currentUser = await IzendaUtilities.DeactivateIzendaUser(token, userDetail); } if (!currentUser.Active && userDetail.Active) { currentUser = await IzendaUtilities.ActivateIzendaUser(token, userDetail); } if (currentUser.Active == userDetail.Active) { success = await IzendaUtilities.SaveIzendaUser(token, currentUser); } } if (currentUser.Active == userDetail.Active) { success = await IzendaUtilities.SaveIzendaUser(token, currentUser); } if (success) { var combinedList = CacheSystem.GetCacheItem("combinedList") as List <UserDetail>; var duplicateUserDetail = combinedList.FirstOrDefault(e => e.EmailAddress == userDetail.EmailAddress); combinedList.Remove(duplicateUserDetail); combinedList.Add(userDetail); return(PartialView("ActiveDirectoryList", combinedList)); } } catch (Exception e) { Console.WriteLine(e); throw; } return(View(userDetail)); } else { ViewBag.SystemAdmin = false; var identity = (System.Security.Claims.ClaimsIdentity)User.Identity; var claims = identity.Claims; string SystemAdmin = claims.FirstOrDefault(x => x.Type == "SystemAdmin")?.Value; if (SystemAdmin == "True") { ViewBag.SystemAdmin = true; } var token = GetToken(); var roles = await IzendaUtilities.GetRoles(token); var employeeList = CacheSystem.GetCacheItem("combinedList") as List <UserDetail>; var employee = (from e in employeeList where e.EmailAddress == userDetail.EmailAddress select e).FirstOrDefault(); var userRoles = roles.Where(t => t.Users.Contains(employee)).ToList(); var userRolesIds = new string[userRoles.Count]; var length = userRoles.Count; for (var i = 0; i < length; i++) { userRolesIds[i] = userRoles[i].Id.ToString(); } var rolesList = new MultiSelectList(roles.ToList().OrderBy(i => i.Name), "Id", "Name", userRolesIds); employee.RoleOptions = rolesList; return(View(employee)); } }
public ActionResult AddComponent() { ViewData["Categories"] = new MultiSelectList(_frameworxProjectService.GetAllCategories(), "Id", "Name"); return(View()); }
public ActionResult Create(CompetitorViewModel competitorViewModel, HttpPostedFileBase competitorPhoto) { if (competitorPhoto != null) { // An array of allowed extensions var acceptedExtentions = new[] { ".png", ".jpg", ".jpeg", ".gif" }; // Get extention of the file var fileExtension = Path.GetExtension(competitorPhoto.FileName).ToLower(); if (!acceptedExtentions.Contains(fileExtension)) { ModelState.AddModelError(string.Empty, "File is not a valid type!"); } // Check if the file has any content. A 0 byte file will return invalid to the view if (competitorPhoto.ContentLength < 1) { ModelState.AddModelError("", "Error uploading file, file is empty or corrupt!"); } } if (ModelState.IsValid) { // Populate competitor object with form data Competitor competitor = competitorViewModel.Competitor; // Convert email to lowercase competitor.competitorEmail = competitor.competitorEmail.ToLower(); if (competitorViewModel.SelectedGames != null) { foreach (var gameID in competitorViewModel.SelectedGames) { // Find the game by ID Game game = db.Games.Find(gameID); competitor.Games.Add(game); } } if (competitorPhoto != null) { var fileExtension = Path.GetExtension(competitorPhoto.FileName).ToLower(); string fileNamePattern = @"\s|[().,]"; var fileName = Regex.Replace(competitor.competitorName, fileNamePattern, string.Empty) + fileExtension; try { competitorPhoto.SaveAs(Path.Combine(HttpContext.Server.MapPath("~/Upload/Photos"), fileName)); competitor.competitorPhotoPath = "/Upload/Photos/" + fileName; } catch { // Show an error if file couldn't be saved for whatever reason // In a more traditional application the exception would be logged, however I am not doing that here ModelState.AddModelError("", "File could not be saved, please contact the administrator!"); } } // Verify the ModelState remains valid (try-catch block above could change it) if (ModelState.IsValid) { // Save changes to the DB db.Competitors.Add(competitor); db.SaveChanges(); return(RedirectToAction("Index")); } } // Repopulate the ViewBag/AllGames variables if the form is not valid and has to be re-displayed MultiSelectList gamesList = new MultiSelectList(db.Games, "gameID", "gameName"); competitorViewModel.AllGames = gamesList; ViewBag.countryList = GetCountries(); ViewBag.titlesList = GetTitles(); ViewBag.genderList = GetGenders(); return(View(competitorViewModel)); }
//Extension public static MvcHtmlString CheckBoxListFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, IEnumerable <TProperty> > > expression, MultiSelectList allOptions, object htmlAttributes = null) { ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression <TModel, IEnumerable <TProperty> >(expression, htmlHelper.ViewData); // Derive property name for checkbox name string propertyName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(modelMetadata.PropertyName); // Get currently select values from the ViewData model IEnumerable <TProperty> list = expression.Compile().Invoke(htmlHelper.ViewData.Model); // Convert selected value list to a List<string> for easy manipulation IList <string> selectedValues = new List <string>(); if (list != null) { selectedValues = new List <TProperty>(list).ConvertAll <string>(delegate(TProperty i) { return(i.ToString()); }); } // Create div TagBuilder divTag = new TagBuilder("div"); divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true); // Add checkboxes foreach (SelectListItem item in allOptions) { divTag.InnerHtml += string.Format( "<div><input type=\"checkbox\" onclick=\"OnCheck('{0}_{2}','{0}');\" name=\"{0}_{2}\" id=\"{1}_{2}\" " + "value=\"{2}\" {3} /><label for=\"{1}_{2}\">{4}</label></div>" + "<input type='hidden' name='{0}' id='{0}' value='{5}' />" //August , propertyName, TagBuilder.CreateSanitizedId(propertyName), item.Value, selectedValues.Contains(item.Value) ? "checked=\"checked\"" : string.Empty, item.Text, selectedValues.FirstOrDefault().nullAs("N") ); } return(MvcHtmlString.Create(divTag.ToString())); }
public void Constructor2SetsProperties() { // Arrange IEnumerable items = new object[0]; IEnumerable selectedValues = new object[0]; // Act MultiSelectList multiSelect = new MultiSelectList(items, selectedValues); // Assert Assert.Same(items, multiSelect.Items); Assert.Null(multiSelect.DataValueField); Assert.Null(multiSelect.DataTextField); Assert.Same(selectedValues, multiSelect.SelectedValues); }