My function to pass roles to combobox in the custom form layout where the combobox is defined
private List<Role> GetRoles()
{
return db.Roles.ToList();
}
//this will pass a list of roles to the front end
ViewData["Roles"] = GetRoles();
Custom form layout this combox will then load a list of roles from the database table
#Html.DevExpress().ComboBox(ComboBoxsettings =>
{
Gsettings.Name = "Id";
ComboBoxsettings.Name = "RoleId";
ComboBoxsettings.Width = 500;
ComboBoxsettings.SelectedIndex = 1;
ComboBoxsettings.Properties.TextField = "Name";
ComboBoxsettings.Properties.ValueField = "Id";
ComboBoxsettings.Properties.DropDownStyle =
DropDownStyle.DropDown;
ComboBoxsettings.ShowModelErrors = true;
}
).BindList(ViewData["Roles"]).Render();
Related
I am using a Modal Partial View in my app. I am validating my model if it has errors I am returning the model using ModelState.AddModelError() but it is not working fine. Also, I could not load the SelectLists.
public ActionResult StockOut(StockOut model)
{
if (ModelState.IsValid)
{
var stock = (from s in db.Stocks where s.ProductId == model.ProductId select s).FirstOrDefault();
if (stock.Quantity > 0 && model.Quantity <= stock.Quantity)
{
var weight = ((from p in db.Products where p.Id == model.ProductId select p).FirstOrDefault().NetWeight) * model.Quantity;
stock.Quantity -= model.Quantity;
stock.TotalWeight -= weight;
StockOut entity = new StockOut()
{
DriverId = model.DriverId,
LastUpdated = DateTime.Now,
ProductId = model.ProductId,
Quantity = model.Quantity,
TotalWeight = weight
};
db.StockOut.Add(entity);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("Quantity", "Please Enter A Valid Quantity");
ViewBag.ProductId = new SelectList(db.Products.ToList(), model.ProductId);
ViewBag.DriverId = new SelectList(db.Products.ToList(), model.DriverId);
}
}
ViewBag.ProductId = new SelectList(db.Products.ToList(), model.ProductId);
ViewBag.DriverId = new SelectList(db.Users.ToList(), model.DriverId);
return PartialView(model);
}
Before Submitting:
After Getting an Error
fix you select lists, you are creating them twice, remove one set (inside of if)
ViewBag.ProductId = new SelectList(db.Products.ToList(),"Id", "Name" , model.ProductId);
///Are you sure that you have have to use products again?
ViewBag.DriverId = new SelectList(db.Products.ToList(),"Id",
"Name" , model.DriverId);
and if you want to use AddModelError you have to add to form
#Html.ValidationSummary(false)
I was able to fetch the options for select type of fields using the following code.
for(index in fieldNames) {
var selectFields = {};
var field = record.getField(fieldNames[index]);
if(field != null) {
var id = field.getName();
var field_details = {}
field_details['Type']= field.getType();
field_details['Label'] = field.getLabel();
if(field.getType() == 'select') {
var Options = field.getSelectOptions();
var selectOptions = {};
for(var i in Options) {
var opt_id = Options[i].getId();
selectOptions[opt_id] = Options[i].getText();
}
field_details['Options'] = selectOptions;
}
selectFields[id]=field_details;
}
}
I can successfully fetch options such as customform, salesrep, and shipmethod. What I cannot retrieve is the item list to be added in the sales order. Based from what I can see in the docs, there's a sublist and subrecord, but there's no similar method to what I'm using right now which is the getSelectOptions method.
By the way, I'm using this as a RESTlet.
How to set date from one dateEdit to another.
I have two dateedit properties. When one dateEdit (date1) changes i need to set some value on another dateedit. I have created ondatechanged function which has some logics and then i need to set the value to date2 field. i have used js/jquery to set but the value does not bind properly after focusing or clicking the changed date2 Dateedit.
In my View
#Html.Hidden("dateTemp")
<label>R2Date</label>
#Html.DevExpress().DateEdit(
settings =>
{
settings.Name = "date1";
settings.Properties.NullText = "MM/dd/yyyy";
settings.Properties.EditFormat = EditFormat.Custom;
settings.Properties.EditFormatString = "MM/dd/yyyy";
settings.Width = System.Web.UI.WebControls.Unit.Percentage(27);
settings.Properties.ClientSideEvents.DateChanged = "OnDateChanged";
}).Bind(Model.r2date).GetHtml()
<label>RDate</label>
#Html.DevExpress().DateEdit(
settings =>
{
settings.Name = "date2";
settings.Properties.NullText = "MM/dd/yyyy";
settings.Properties.EditFormat = EditFormat.Custom;
settings.Properties.EditFormatString = "MM/dd/yyyy";
settings.Width = System.Web.UI.WebControls.Unit.Percentage(27);
settings.Properties.ClientSideEvents.DateChanged = "ReportOnDateChanged";
}).Bind(Model.date1).GetHtml()
[JScript]
function OnDateChanged(s, e) {
var dateVal = s.GetText();
//my logic here
dateOnchange();
}
dateOnchange(){
//my logic here just need to call reportondatechange()
ReportOnDateChanged();
}
function ReportOnDateChanged(s,e )
{
dateVal1 = $("#dateTemp").val(); //dateval1 has some values here
s.SetDate(dateVal1);//not working how to set the value here
}
https://documentation.devexpress.com/#AspNet/DevExpressWebScriptsASPxClientControl_GetControlCollectiontopic
This should do it
var editor = ASPxClientControl.GetControlCollection().GetByName("date2");
if (editor) {
editor.SetValue(dateVal1);
}
$("#date2").val(dateVal1);
I'm following this post
This is a simple application where administrators can prepare a questionnaire and prepare a simple survey and share it with whoever registered on our website.
Once the survey is completed by end users, the web site administrator (or whoever is authorized) can analyze the survey results and other feedback in any form like graphical or textual.
-- but there are some thing broken in it--
when you add a question you choose the type of question, so I made this class
public enum QuestionTypes
{
SingleLineTextBox, // will render a textbox
MultiLineTextBox, // will render a text area
YesOrNo, //will render a checkbox
SingleSelect, //will render a dropdownlist
MultiSelect //will render a listbox
}
and saved it in the database as a string but it renders in runtime in a different way ( the textbox ,SingleLineTextBox ,YesOrNo work well but MultiSelect and YesOrNo do not work )
This application uses entity framework - there is a section to add a question. It looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlTypes.Items.Add(QuestionTypes.SingleLineTextBox.ToString());
ddlTypes.Items.Add(QuestionTypes.MultiLineTextBox.ToString());
ddlTypes.Items.Add(QuestionTypes.SingleSelect.ToString());
ddlTypes.Items.Add(QuestionTypes.MultiSelect.ToString());
ddlTypes.Items.Add(QuestionTypes.YesOrNo.ToString());
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SurveyAppConString context = new SurveyAppConString();
Question quest = new Question();
quest.Text = txtTitle.Text.Trim();
quest.QuestionType = ddlTypes.SelectedItem.Text;
quest.Options = txtValues.Text.Trim();
context.AddToQuestions(quest);
context.SaveChanges();
}
After that you can assign any question to survey and there's a page to display all surveys. It is broken there. I want to create a checkbox in run time and take his value as a string and save it in database and make the same thing with a listbox too
This is sample code ( works for textboxes and dropdownlist)
private void PopulateSurvey()
{
btnSubmit.Enabled = true;
List<Question> questions = (from p in context.Questions
join q in context.SurveyQuestions on p.ID equals q.QuestionID
where q.SurveyID == surveyid
select p).ToList();
Table tbl = new Table();
tbl.Width = Unit.Percentage(100);
TableRow tr;
TableCell tc;
TextBox txt;
CheckBox cbk;
DropDownList ddl;
foreach (Question q in questions)
{
tr = new TableRow();
tc = new TableCell();
tc.Width = Unit.Percentage(25);
tc.Text = q.Text;
tc.Attributes.Add("id", q.ID.ToString());
tr.Cells.Add(tc);
tc = new TableCell();
if (q.QuestionType.ToLower() == "singlelinetextbox")
{
txt = new TextBox();
txt.ID = "txt_" + q.ID;
txt.Width = Unit.Percentage(40);
tc.Controls.Add(txt);
}
if (q.QuestionType.ToLower() == "multilinetextbox")
{
txt = new TextBox();
txt.ID = "txt_" + q.ID;
txt.TextMode = TextBoxMode.MultiLine;
txt.Width = Unit.Percentage(40);
tc.Controls.Add(txt);
}
if (q.QuestionType.ToLower() == "singleselect")
{
ddl = new DropDownList();
ddl.ID = "ddl_" + q.ID;
ddl.Width = Unit.Percentage(41);
if (!string.IsNullOrEmpty(q.Options))
{
string[] values = q.Options.Split(',');
foreach (string v in values)
ddl.Items.Add(v.Trim());
}
tc.Controls.Add(ddl);
}
tc.Width = Unit.Percentage(80);
tr.Cells.Add(tc);
tbl.Rows.Add(tr);
}
pnlSurvey.Controls.Add(tbl);
}
You can quickly check the full code here and this is a database diagram:
note --
i worked in checkboxes area and added the code like that
i do the code like that
if (q.QuestionType.ToLower() == "yesorno")
{
lblyes = new Label();
lblyes.Text = "yes";
tc.Controls.Add(lblyes);
cbk = new CheckBox();
cbk.ID = "cbk_" + q.ID;
//cbk.value = "true";
cbk.Width=Unit.Percentage(41);
tc.Controls.Add(cbk);
}
// On Postback|Save
sres.Response = (ctrc as CheckBox).Checked ? "yes" : "no";
and it showed like that
it worked fine ( one checkbox )
to make two checkbox ( it's better to create aradiobutton)
i created and worked fine
if (q.QuestionType.ToLower() == "yesorno")//this is the name you create it when add anew question type
{
lblyes = new Label();
lblyes.Text = "yes";
tc.Controls.Add(lblyes);
rbk = new RadioButton();
rbk.ID = "rbk_" + q.ID;
rbk.GroupName = "rbyesno";
rbk.Width = Unit.Percentage(41);
tc.Controls.Add(rbk);
//add another chexbox and label
lblno = new Label();
lblno.Text = "no";
tc.Controls.Add(lblno);
rbk = new RadioButton();
rbk.ID = "cbk_1" + q.ID;
rbk.GroupName = "rbyesno";
rbk.Width = Unit.Percentage(41);
tc.Controls.Add(rbk);
}
// On Postback|Save
else if (ctrc is RadioButton)
{
//sres.Response = (ctrc as CheckBox).Checked.ToString();
sres.Response = (ctrc as RadioButton).Checked ? "no" : "yes";
}
We check on last radiobutton ( as created after the first one)
--- now i just need to create a list to select multiple choices from form and send it as a string to database
--- when i try to add alistbox so colud add a multible select quesion type to asurvey
this is asnippet of code
if (q.QuestionType.ToLower() == "MultiSelect")
{
lstmulti = new ListBox();
lstmulti.ID = "lst_" + q.ID;
lstmulti.Width = Unit.Percentage(41);
//lstmulti.Items.Add("on");
//lstmulti.Items.Add("sgsd");
//lstmulti.Items.Add("thre");
if (!string.IsNullOrEmpty(q.Options))
{
string[] values = q.Options.Split(',');
foreach (string v in values)
lstmulti.Items.Add(v.Trim());
}
tc.Controls.Add(lstmulti);
}
in save
else if (ctrc is ListBox)
{
//sres.Response = (ctrc as ListBox).SelectionMode.ToString();
sres.Response = (ctrc as ListBox).SelectedValue;
}
it didn't work at all
and it didn't render too as alistbox
//create list in run time
if (q.QuestionType.ToLower() == "MultiSelect")
{
ListBox lstmulti = new ListBox();
lstmulti.ID = "lst_" + q.ID;
lstmulti.Width = Unit.Percentage(41);
lstmulti.Height = Unit.Percentage(100);
lstmulti.SelectionMode = ListSelectionMode.Multiple;
//to select multible choices and send to database
if (lstmulti.SelectionMode == ListSelectionMode.Multiple)
{
var selected = new List<string>();
for (int i = 0; i < lstmulti.Items.Count; i++)
{
if (lstmulti.Items[i].Selected)
selected.Add(lstmulti.Items[i].Text);
string selectedItem = lstmulti.Items[i].Text;
//insert command
///it should send the result to databse where the table name is Survey_Response and column is Response
//SurveyAppConString db=new SurveyAppConString();
// //db.Survey_Response.Include(m => m.Response) = string.Join(",", selected);
}
}
if (!string.IsNullOrEmpty(q.Options))
{
string[] values = q.Options.Split(',');
foreach (string v in values)
lstmulti.Items.Add(v.Trim());
}
tc.Controls.Add(lstmulti);
}
//in post-save
else if (ctrc is ListBox)
{
//sres.Response = (ctrc as ListBox).SelectionMode.ToString();
sres.Response = (ctrc as ListBox).Items.ToString();
}
notes :: i'm using asp.net webform with entity framwork
For the listbox you'll have to set the SelectionMode to multiple and set the size to render. On postback if the SelectionMode is multiple then you will need to loop the items and concatenate the results.
if (myListBox.SelectionMode == SelectionMode.Multiple)
{
var selected = new List<string>();
foreach (var item in myListBox.Items)
if (item.Selected)
selected.Add(item.Text);
response = string.Join(",", selected);
}
You can easily follow the example and add a checkbox control with a "true" value. The issue is that unchecked checkboxes are not passed as form values so you could either set it to a default "false" if the form name does not exist in the form post, or you can set a hidden default value after the checkbox field and use the first passed value
Model binding in MVC will do this for you
https://stackoverflow.com/a/14731571/60669
Since the script is just looking at the Server controls its even simpler
if (q.QuestionType.ToLower() == "yesorno")
{
var cb = new Checkbox();
cb.Id = "cb_" + q.id;
cb.Value = "true;
// add to table cell
}
// On Postback|Save
if (ctrl is Checkbox)
{
sres.Result = (ctrl as Checkbox).Checked ? "true" : "false"
}
the listbox didn't render because of syntax error
in general the worked code are here
//create list in run time
if (q.QuestionType == "MultiSelect")
{
lstmulti = new ListBox();
lstmulti.ID = "lst_" + q.ID;
lstmulti.Width = Unit.Percentage(41);
lstmulti.Height = Unit.Percentage(100);
lstmulti.SelectionMode = ListSelectionMode.Multiple;
//to retrive the option values
if (!string.IsNullOrEmpty(q.Options))
{
string[] values = q.Options.Split(',');
foreach (string v in values)
lstmulti.Items.Add(v.Trim());
}
tc.Controls.Add(lstmulti);
}
tc.Width = Unit.Percentage(80);
tr.Cells.Add(tc);
tbl.Rows.Add(tr);
}
pnlSurvey.Controls.Add(tbl);
}
in save
else if (ctrc is ListBox)
{
var selected = new List<string>();
for (int i = 0; i < lstmulti.Items.Count; i++)
{
if (lstmulti.Items[i].Selected)
selected.Add(lstmulti.Items[i].Text);
string selectedItem = lstmulti.Items[i].Text;
sres.Response = string.Join(",", selected) ;
}
}
}
Can anyone help me to get the user info from a person column using javascript? So far I have been able to read the list item and return a SP.FieldUserValue from which I can get a numeric Id (not sure what this ID is) and the display name. e.g.
var ManVal = oListItem.get_item("RecruitingManager").get_lookupValue();
var ManId = oListItem.get_item("RecruitingManager").get_lookupId();
How do I take this one step further to create a sp user object?
Ultimately what I'm trying to achieve is to retrieve the details from the list and then populate a people editor.
Ok, I've got it.
Here is my code, hope it helps somebody. I haven't included the method to retrieve the list item, just the line from that function where I'm getting the value of the person.
var _lineManager;
var lineManager = oListItem.get_item("RecruitingManager").get_lookupId();
_lineManager = oWebsite.getUserById(lineManager);
getLineManager();
function getLineManager() {
context.load(_lineManager);
context.executeQueryAsync(onGetUserNameSuccessLM, onGetUserNameFailLM);
}
function onGetUserNameSuccessLM() {
alert(lineManager.get_title());
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = false;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
var users = new Array(1);
var defaultUser = new Object();
defaultUser.AutoFillDisplayText = lineManager.get_title();
defaultUser.AutoFillKey = lineManager.get_loginName();
defaultUser.Description = lineManager.get_email();
defaultUser.DisplayText = lineManager.get_title();
defaultUser.EntityType = "User";
defaultUser.IsResolved = true;
defaultUser.Key = lineManager.get_loginName();
defaultUser.Resolved = true;
users[0] = defaultUser;
SPClientPeoplePicker_InitStandaloneControlWrapper('peoplePickerDivLinMan', users, schema);
}
function onGetUserNameFailLM(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
The person field (actually called "people picker") has a specific JavaScript function which you might find useful: GetAllUserInfo()
There is a nice article on MSDN:
How to: Use the client-side People Picker control in apps for SharePoint
The relevant code is:
// Get the people picker object from the page.
var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
var userInfo = '';
for (var i = 0; i < users.length; i++) {
var user = users[i];
for (var userProperty in user) {
userInfo += userProperty + ': ' + user[userProperty] + '<br>';
}
}
$('#resolvedUsers').html(userInfo);
// Get user keys.
var keys = peoplePicker.GetAllUserKeys();
$('#userKeys').html(keys);
So basically you have to cast your field to a SPClientPeoplePicker and can then use GetAllUserInfo to iterate over all users in the field.