I'm trying to either have a text box, that shows description when user picks the corresponding id on a ComboBox. Or alternately to show ID - Description in the same ComboBox.
Any idea how achieve this?
Find below with Telerik controls
C# Razor
<div class="row">
<div class="col-md-8">
#(Html.Kendo().DropDownList()
.Name("color")
.DataTextField("Text")
.DataValueField("Value")
.Events(e => e.Change("change"))
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Black",
Value = "1"
},
new SelectListItem() {
Text = "Orange",
Value = "2"
},
new SelectListItem() {
Text = "Grey",
Value = "3"
}
})
.Value("1")
.HtmlAttributes(new { style = "width: 100%" })
)
</div>
<div class="col-md-4">
#Html.Kendo().TextBox().Name("txtColor")
</div>
</div>
Script
<script>
function change() {
$("#txtColor").val($("#color").val());
}
</script>
I am trying to save a multi select list on my user create in MVC 5, but the values are not saving. Values are saving only in edit. For some reason it's not working on create and it seems the issue is tied to the identity user. I have the same method implemented in a different controller for another entity and it's working fine.
I am trying to assign multiple health professionals to a user in the below code. I am not getting any errors or a break on save, it just doesn't save the values.
Can anyone please have a look at my code and give me a solution to this problem.
Here is my controller code relevant to creating a user:
public ActionResult Create()
{
PopulateDepartmentsDropDownList();
PopulateSuperiorsDropDownList();
// Show a list of available groups:
ViewBag.GroupsList = new SelectList(this.GroupManager.Groups, "Id", "Name");
var applicationUser = new ApplicationUser();
applicationUser.HealthProfessionals = new List<HealthProfessional>();
PopulateAssignedHealthProfessionals(applicationUser);
return View();
}
[HttpPost]
public async Task<ActionResult> Create([Bind(Exclude = "ProfilePicture")]RegisterViewModel userViewModel, ApplicationUser applicationUser, string[] selectedHealthProfessionals, params string[] selectedGroups)
{
if (selectedHealthProfessionals != null)
{
applicationUser.HealthProfessionals = new List<HealthProfessional>();
foreach (var healthProfessional in selectedHealthProfessionals)
{
var healthProfessionalToAdd = db.HealthProfessionals.Find(int.Parse(healthProfessional));
applicationUser.HealthProfessionals.Add(healthProfessionalToAdd);
}
}
if (ModelState.IsValid)
{
// To convert the user uploaded Photo as Byte Array before save to DB
byte[] imageData = null;
if (Request.Files.Count > 0)
{
HttpPostedFileBase poImgFile = Request.Files["UserPhoto"];
using (var binary = new BinaryReader(poImgFile.InputStream))
{
imageData = binary.ReadBytes(poImgFile.ContentLength);
}
}
var user = new ApplicationUser
{
UserName = userViewModel.Email,
FirstName = userViewModel.FirstName,
LastName = userViewModel.LastName,
Position = userViewModel.Position,
DepartmentID = userViewModel.DepartmentID,
SuperiorID = userViewModel.SuperiorID,
OfficeNumber = userViewModel.OfficeNumber,
CellNumber = userViewModel.CellNumber,
Email = userViewModel.Email
};
//Here we pass the byte array to user context to store in db
user.ProfilePicture = imageData;
var adminresult = await UserManager
.CreateAsync(user, userViewModel.Password);
//Add User to the selected Groups
if (adminresult.Succeeded)
{
if (selectedGroups != null)
{
selectedGroups = selectedGroups ?? new string[] { };
await this.GroupManager
.SetUserGroupsAsync(user.Id, selectedGroups);
}
return RedirectToAction("Users");
}
}
ViewBag.Groups = new SelectList(await RoleManager.Roles.ToListAsync(), "Id", "Name");
PopulateDepartmentsDropDownList(userViewModel.DepartmentID);
PopulateSuperiorsDropDownList(userViewModel.SuperiorID);
PopulateAssignedHealthProfessionals(applicationUser);
return View(applicationUser);
}
private void PopulateAssignedHealthProfessionals(ApplicationUser applicationUser)
{
var allHealthProfessionals = db.HealthProfessionals;
var userHealthProfessionals = new HashSet<int>(applicationUser.HealthProfessionals.Select(i => i.HealthProfessionalID));
var viewModel = new List<AssignedHealthProfessionals>();
foreach (var healthProfessional in allHealthProfessionals)
{
viewModel.Add(new AssignedHealthProfessionals
{
HealthProfessionalID = healthProfessional.HealthProfessionalID,
HealthProfessionalName = healthProfessional.Name,
HealthProfessionalSurname = healthProfessional.Surname,
Assigned = userHealthProfessionals.Contains(healthProfessional.HealthProfessionalID)
});
}
ViewBag.HealthProfessionals = viewModel;
}
Here is my create view:
#model MyApp.Models.RegisterViewModel
#{
ViewBag.Title = "Create User";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="#Url.Content("~/Content/CSS/dropify.min.css")" rel="stylesheet" type="text/css" />
<div class="m-grid__item m-grid__item--fluid m-wrapper">
<div class="m-subheader ">
<div class="d-flex align-items-center">
<div class="mr-auto">
<h3 class="m-subheader__title m-subheader__title--separator">
Add User
</h3>
<ul class="m-subheader__breadcrumbs m-nav m-nav--inline">
<li class="m-nav__item m-nav__item--home">
<a href="#Url.Action("Dashboard","Home")" class="m-nav__link m-nav__link--icon">
<i class="m-nav__link-icon la la-home"></i>
</a>
</li>
<li class="m-nav__separator">
-
</li>
<li class="m-nav__item">
<a href="#Url.Action("Users","UserManagement")" class="m-nav__link">
<span class="m-nav__link-text">
Users
</span>
</a>
</li>
</ul>
</div>
<div>
</div>
</div>
</div>
#using (Html.BeginForm("Create", "UserManagement", FormMethod.Post, new { #class = "m-form m-form--fit m-form--label-align-right", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="m-content">
<div class="m-portlet m-portlet--mobile">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
User Details
</h3>
</div>
</div>
</div>
<div class="m-portlet__body">
<div class="m-form__section m-form__section--first">
<div class="row">
<div class="col-lg-4">
<div class="form-group">
<label>
Email Address
</label>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label>
First Name
</label>
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label>
Last Name
</label>
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.LastName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="form-group">
<label>
Position
</label>
#Html.TextBoxFor(m => m.Position, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Position, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label>
Department
</label>
#Html.DropDownList("DepartmentID", null, "Choose Department", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.DepartmentID, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label>
Superior
</label>
#Html.DropDownList("SuperiorID", null, "Choose Superior", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.SuperiorID, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>
Password
</label>
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>
Confirm Password
</label>
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>
Office Number
</label>
#Html.TextBoxFor(m => m.OfficeNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.OfficeNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>
Cell Number
</label>
#Html.TextBoxFor(m => m.CellNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.CellNumber, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>
User Groups
</label>
<div class="m-checkbox-list">
#foreach (var item in (SelectList)ViewBag.GroupsList)
{
<label class="m-checkbox m-checkbox--success">
<input type="checkbox" name="selectedGroups" value="#item.Value">
#Html.Label(item.Text, new { #class = "control-label" })
<span></span>
</label>
}
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>
Health Professionals
</label>
<div class="m-checkbox-list">
#{
int cnt = 0;
List<MyApp.ViewModels.AssignedHealthProfessionals> healthProfessionals = ViewBag.HealthProfessionals;
foreach (var healthProfessional in healthProfessionals)
{
if (cnt++ % 3 == 0)
{
}
<label class="m-checkbox m-checkbox--success">
<input type="checkbox" name="selectedHealthProfessionals" value="#healthProfessional.HealthProfessionalID" #(Html.Raw(healthProfessional.Assigned ? "checked=\"checked\"" : ""))>
#Html.Label(healthProfessional.HealthProfessionalName, new { #class = "control-label" }) #Html.Label(healthProfessional.HealthProfessionalSurname, new { #class = "control-label" })
<span></span>
</label>
}
}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label>
Profile Picture
</label>
<input type="file" name="UserPhoto" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" class="dropify" />
</div>
</div>
</div>
</div>
</div>
</div>
<div class="m-portlet__body">
<!-- Form Actions Start -->
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
Actions
</h3>
</div>
</div>
</div>
<div class="m-portlet__foot m-portlet__foot--fit">
<div class="m-form__actions">
<input type="submit" class="btn btn-accent m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill" value="Save" />
#Html.ActionLink("Cancel", "Users", null, new { #class = "btn m-btn--pill m-btn--air btn-brand m-btn m-btn--custom" })
</div>
</div>
</div>
<!-- Form Actions End -->
</div>
</div>
}
</div>
<script src="#Url.Content("~/Scripts/jquery.min.js")"></script>
<script src="#Url.Content("~/Scripts/dropify.min.js")"></script>
<script>
$(document).ready(function () {
// Basic
$('.dropify').dropify();
// Translated
$('.dropify-fr').dropify({
messages: {
default: 'Glissez-déposez un fichier ici ou cliquez',
replace: 'Glissez-déposez un fichier ou cliquez pour remplacer',
remove: 'Supprimer',
error: 'Désolé, le fichier trop volumineux'
}
});
// Used events
var drEvent = $('#input-file-events').dropify();
drEvent.on('dropify.beforeClear', function (event, element) {
return confirm("Do you really want to delete \"" + element.file.name + "\" ?");
});
drEvent.on('dropify.afterClear', function (event, element) {
alert('File deleted');
});
drEvent.on('dropify.errors', function (event, element) {
console.log('Has Errors');
});
var drDestroy = $('#input-file-to-destroy').dropify();
drDestroy = drDestroy.data('dropify')
$('#toggleDropify').on('click', function (e) {
e.preventDefault();
if (drDestroy.isDropified()) {
drDestroy.destroy();
} else {
drDestroy.init();
}
})
});
</script>
Here is the controller for the edit function which works:
public async Task<ActionResult> Edit(int id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser applicationUser = db.Users.Include(h => h.HealthProfessionals).Where(h => h.Id == id).Single();
PopulateAssignedHealthProfessionals(applicationUser);
var user = await UserManager.FindByIdAsync(id);
if (user == null)
{
return HttpNotFound();
}
// Display a list of available Groups:
var allGroups = this.GroupManager.Groups;
var userGroups = await this.GroupManager.GetUserGroupsAsync(id);
var model = new EditUserViewModel()
{
Id = user.Id,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
Position = user.Position,
DepartmentID = user.DepartmentID,
SuperiorID = user.SuperiorID,
OfficeNumber = user.OfficeNumber,
CellNumber = user.CellNumber
};
foreach (var group in allGroups)
{
var listItem = new SelectListItem()
{
Text = group.Name,
Value = group.Id,
Selected = userGroups.Any(g => g.Id == group.Id)
};
model.GroupsList.Add(listItem);
}
PopulateDepartmentsDropDownList(user.DepartmentID);
PopulateSuperiorsDropDownList(user.SuperiorID);
return View(model);
}
private void PopulateAssignedHealthProfessionals(ApplicationUser applicationUser)
{
var allHealthProfessionals = db.HealthProfessionals;
var userHealthProfessionals = new HashSet<int>(applicationUser.HealthProfessionals.Select(i => i.HealthProfessionalID));
var viewModel = new List<AssignedHealthProfessionals>();
foreach (var healthProfessional in allHealthProfessionals)
{
viewModel.Add(new AssignedHealthProfessionals
{
HealthProfessionalID = healthProfessional.HealthProfessionalID,
HealthProfessionalName = healthProfessional.Name,
HealthProfessionalSurname = healthProfessional.Surname,
Assigned = userHealthProfessionals.Contains(healthProfessional.HealthProfessionalID)
});
}
ViewBag.HealthProfessionals = viewModel;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Email,Id,FirstName,LastName,Position,DepartmentID,SuperiorID,OfficeNumber,CellNumber", Exclude = "ProfilePicture")] EditUserViewModel editUser, ApplicationUser applicationUser, int? id, string[] selectedHealthProfessionals, params string[] selectedGroups)
{
if (ModelState.IsValid)
{
// To convert the user uploaded Photo as Byte Array before save to DB
byte[] imageData = null;
if (Request.Files.Count > 0)
{
HttpPostedFileBase poImgFile = Request.Files["UserPhoto"];
using (var binary = new BinaryReader(poImgFile.InputStream))
{
imageData = binary.ReadBytes(poImgFile.ContentLength);
}
}
var user = await UserManager.FindByIdAsync(editUser.Id);
if (user == null)
{
return HttpNotFound();
}
var applicationUserToUpdate = db.Users.Include(h => h.HealthProfessionals).Where(h => h.Id == id).Single();
if (TryUpdateModel(applicationUserToUpdate, "",
new string[] { }))
{
try
{
UpdateUserHealthProfessionals(selectedHealthProfessionals, applicationUserToUpdate);
db.SaveChanges();
return RedirectToAction("Users");
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateAssignedHealthProfessionals(applicationUserToUpdate);
// Update the User:
user.UserName = editUser.Email;
user.Email = editUser.Email;
user.FirstName = editUser.FirstName;
user.LastName = editUser.LastName;
user.Position = editUser.Position;
user.DepartmentID = editUser.DepartmentID;
user.SuperiorID = editUser.SuperiorID;
user.OfficeNumber = editUser.OfficeNumber;
user.CellNumber = editUser.CellNumber;
//Here we pass the byte array to user context to store in db
user.ProfilePicture = imageData;
await this.UserManager.UpdateAsync(user);
// Update the Groups:
selectedGroups = selectedGroups ?? new string[] { };
await this.GroupManager.SetUserGroupsAsync(user.Id, selectedGroups);
return RedirectToAction("Users");
}
ModelState.AddModelError("", "Something failed.");
PopulateDepartmentsDropDownList(editUser.DepartmentID);
PopulateSuperiorsDropDownList(editUser.SuperiorID);
return View();
}
It's something strange with parameters in your methods.
Best way is to pass user object as parameter.
https://stackoverflow.com/a/18005264/2114398
For quick fix you can update multi-select parameter manually, by removing selectedHealthProfessionals and selectedGroups parameters from method and then initialize them as local variables
[HttpPost]
public async Task<ActionResult> Create([Bind(Exclude = "ProfilePicture")]RegisterViewModel userViewModel, ApplicationUser applicationUser)
{
var selectedGroups = (Request.Form["selectedGroups"] ?? "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var selectedHealthProfessionals = (Request.Form["selectedHealthProfessionals"] ?? "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
applicationUser.HealthProfessionals = new List<HealthProfessional>();
foreach (var healthProfessional in selectedHealthProfessionals)
{
var healthProfessionalToAdd = db.HealthProfessionals.Find(int.Parse(healthProfessional));
applicationUser.HealthProfessionals.Add(healthProfessionalToAdd);
}
if (ModelState.IsValid)
{
...
I am using ajax to send values to my controller from the view:
View where information is collected to send to a different controller:
#using (Html.BeginForm(null, null, FormMethod.Get, htmlAttributes: new { id = "GenerateForm" }))
{
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose AC:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("AC", null, "-- Select AC --", htmlAttributes: new { id = "AC", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose Month:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Months", null, "-- Select Month --", htmlAttributes: new { id = "Month", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Year:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Years", null, "-- Select Year --", htmlAttributes: new { id = "Year", #class = "form-control" })
</div>
</div>
</div>
<br />
<input type="submit" id="SendToController" class="btn btn-primary" value="Generate" />
}
<script type="text/javascript">
$('#SendToController').on('click', function() {
sendToController();
return false;
});
function sendToController(){
var selectedAC = $('#AC').val();
var selectedMonth = $('#Month').val();
var chosenYear = $('#Year').val();
$.ajax({
url: '/MonthReports/Generate',
data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
type: 'GET',
cache: false,
success: function(data){},
});
}
Controller Method:
public ActionResult Generate(int id, int monthValue, string year)
{
List<DailySum> lstDailySum = db.DailySum.Where(x => x.AID == id && x.Day.Month == monthValue + 1 && x.Day.Year.ToString() == year && x.deleted == false).ToList();
List<string> lstInc = lstDailySum.Select(x => x.codeAC.text).Distinct().ToList();
List<MReport> lstMReport = new List<MReport>();
foreach (var inc in lstInc)
{
MReport mReport = new MReport();
mReport.Inc = inc;
mReport.Count = lstDailySum.Where(x => x.codeAC.text == incident).Count();
lstMReport.Add(mReport);
}
return View(lstMReport);
}
Now the values are being passed through when the button is clicked, and the whole method works, except the View doesn't show up.. it just stays on the View where the button was originally clicked... no Generate View appears.
I have placed a breakpoint on the Generate view and it does get hit but the view doesn't show?
I don't know how else to explain it.. the cshtml code is hit with a breakpoint, but the page doesn't show.. it just stays on the page where the button was clicked.
Any help is appreciated.
Because you are using ajax, you should handle the data in the success callback of your ajax call. The way your code is written, you do nothing with the view. The View is rendered to the data variable.
Try something like this:
$.ajax({
url: '/MonthReports/Generate',
data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
type: 'GET',
cache: false,
success: function(data){
$("body").html(data);
}
});
I need insert custom editor tool for inserting links into rich text. It should work as basic link insert in editor but in dialog window I need treeview with our documents structure for select target of link.
Please can you help me with syntax for get selected text of editor content?
Best regards
David
To get selected text from the Kendo Editor you can use GetRange() method. Syntax is following.(http://docs.kendoui.com/api/web/editor#methods-getRange)
http://jsfiddle.net/vojtiik/Sgtxk/1/
HTML:
<textarea id="editor"></textarea>
<input class="buttonB" type="button" value="Get selected value" />
JS:
var textarea = $("#editor");
textarea.kendoEditor({ value: "Hello Davide, how are you doing !" });
var editor = textarea.data("kendoEditor");
$('.buttonB').click(function () {
alert(editor.getRange());
});
This is second way:
var editor = $("#editor").data('kendoEditor');
var selection = editor.getSelection();
console.log(selection.toString());
#helper RenderTreeview()
{
#(Html.Kendo().TreeView()
.Name("treeview")
.HtmlAttributes(new {#class="demo-section" })
.DataTextField("Name")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Treeview", "Admin")
)
)
)
}
#(Html.Kendo().Window()
.Name("Link")
.Title("Insert link")
.Visible(false)
.Content(#<text>
<div style="margin:10px;">
<span style="width:150px; display:inline-block;">Select Section:</span>
<br />
<br />
<div style=" height:200px; overflow:auto;">
#RenderTreeview()
</div>
<br />
<br />
<span style="width:60px; display:inline-block;"></span><span style="color:red" id="errorMsn">Please highlight text</span><br /><br />
<span style="width:60px; display:inline-block;">Text:</span><input style="width:350px;" type="text" id="Linktext" />
<br />
<br />
<div> <span style="width:60px; display:inline-block;"></span><input type="checkbox" id ="check" /> Open in new window</div>
<div style=" text-align:right;">
<button class="k-dialog-insert k-button" onclick="UpdateContent();" >Insert</button> or
<a class="k-dialog-close k-link" id="btnCancel" href="#">Cancel</a>
</div>
</div>
</text>)
.Draggable()
.Resizable()
.Width(600)
.Modal(true)
)
#(Html.Kendo().EditorFor(x=> x.PageContent.Contents)
.Encode(false)
.HtmlAttributes(new { style = "width: 1020px;height:350px" })
.ImageBrowser(img=> img
.Image("~/Content/Images/{0}")
.Read("Read", "ImageBrowser")
.Create("Create", "ImageBrowser")
.Destroy("Destroy", "ImageBrowser")
.Upload("Upload", "ImageBrowser")
.Thumbnail("Thumbnail", "ImageBrowser"))
.Value(#<text></text>)
.Tools(tools => tools
.Clear()
.Formatting()
.FontName()
.Bold()
.Italic()
.Underline()
.Strikethrough()
.JustifyCenter()
.JustifyLeft()
.JustifyRight()
.Outdent()
.FontColor()
.FontSize()
.InsertOrderedList()
.InsertUnorderedList()
.Indent()
.TableEditing()
.InsertImage()
.ViewHtml()
.CreateLink()
.Unlink()
.CustomButton(cb => cb.Name("myTool").ToolTip("Insert Internal Link").Exec(#<text>
function InserLinkContent() {
var editor = $("#PageContent_Contents").data('kendoEditor');
var selection = editor.getSelection();
var string = selection.toString();
var textbox = document.getElementById('Linktext');
textbox.value = string;
if (string.length > 0) {
document.getElementById('errorMsn').style.display = "none";
}
$("#Link").data("kendoWindow").open().center();
}
</text>))
.CustomButton(cb => cb.Name("custom").ToolTip("Insert a horizontal rule").Exec(#<text>
function(e) {
var editor = $(this).data("kendoEditor");
editor.exec("inserthtml", { value: "<hr />" });
}
</text>))
)
)
}
<script>
function UpdateContent() {
var data = $('#treeview').data('kendoTreeView');
var selectednode = data.dataItem(data.select());
var itemid = selectednode.id;
var text = document.getElementById('Linktext');
var string = text.value.toString();
var checkbox = document.getElementById('check');
var target = "";
if (checkbox.checked) {
target = "target='_blank'";
}
editor.exec("inserthtml", { value: "<a " + target + " href='../ContentPage/1?leftmenu="+itemid+"'>" + string + "</a>" });
$("#Link").data("kendoWindow").close();
}
$('#btnCancel').click(function () {
$("#Link").data("kendoWindow").close();
});
</script>
I had a look at all the related questions but am still unsure. I am a noob and still learning.
I have the view:
<% using (Html.BeginForm("TradeUKKPISearchesDataExtract", "Report")) //action/controller
{ %>
<div style="padding: 10px; background-color: #eeeeee; width: 250px; border: 1px solid #cccccc;">
<div style="float: left; width: 100px; padding-top: 3px;">
<p style="color:Red"><%: Html.DropDownList("Choose a Sunday: ", ((DateTime[])ViewData["Sundays"]).Select(day => new SelectListItem() { Text = day.ToString(), Value = day.ToString() }), "--Select--")%>
</p>
</div>
<div class="clear"></div>
</div>
<div style="text-align:right; width: 272px; padding-top: 30px;">
<input type="submit" id="search-submit" value="Search" />
</div>
when I hit the submit button, where do I set the value that needs to be returned?
in html.BeginForm or in Html.DropDownList?
my action:
[HttpPost]
public ActionResult TradeUKKPISearchesDataExtract(DateTime date)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Title, Total");
var reportData = _reportingService.GetTradeUKKPISearches(date);
foreach (var item in reportData)
{
sb.AppendLine(String.Concat("\"", item.Key, "\", ", item.Value));
}
byte[] textBytes = Encoding.UTF8.GetBytes(sb.ToString());
return File(textBytes, "application/csv", "TradeUKKPISearchesDataExport.csv");
}
thanks
The first parameter of Html.DropDownList() is the HTML element's name and that is how the selected value is identified during the form submit. So you should have it like this
<p style="color:Red">Choose a Sunday:<%: Html.DropDownList("date", ((DateTime[])ViewData["Sundays"]).Select(day => new SelectListItem() { Text = day.ToString(), Value = day.ToString() }), "--Select--")%>
to have the date parameter in your action method correctly populated.