How can i make drop down as read only in the asp.net MVC Pattern version 2 after it filles?
You could use jquery to disable all options in the dropdown.
$("#DropdownID option").attr("disabled","true");
This will show the options, but they are not selectable..
This doesn't work, a disabled dropdownlist does not post it's selected value on a form post, if a model property is bound to the dropdownlist the model's property value will be submitted as a null value.
This is an old post, but... my preferred method is to disable the options, not the control, so that it posts the selected value back.
public static MvcHtmlString SecureDropDownListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
string optionLabel,
object htmlAttributes,
bool alwaysReadonly)
{
bool isReadonly = !CurrentUserCanEdit(expression) || alwaysReadonly;
var attributes = new RouteValueDictionary(htmlAttributes);
if (isReadonly)
{
// This will pick up the style but not prevent a different option from being selected.
attributes.Add("readonly", "readonly");
}
var retval = htmlHelper.DropDownListFor(expression, selectList, optionLabel, attributes);
// Disable all but the selected option in the list; this will allow user to see other options, but not select one
if (isReadonly)
{
retval = new MvcHtmlString(retval.ToHtmlString().Replace("option value=", "option disabled=\"disabled\" value="));
}
return retval;
}
The effect of this is that the user can click the down arrow and see the unselected options, but can't select any of them. Since the select itself is not disabled, only the options, the selected value will be included in the postback.
The following is a solution that can prevent users from making any selection on the dropdownlist and still submit the value of the selected option in a form post.
A dropdownlist marked as readonly.
#Html.DropDownListFor(model => Model.SomeID, new SelectList(ListOfOptions, "Value", "Text", Model.SomeID), new {#class = "disabled", #readonly = "readonly"})
or simply
<select class="disabled" readonly="readonly">...[All your options, one of them selected]...</select>
And then a jquery that will disable the options that are not selected (that is the key).
$('select.disabled option:not(:selected)').attr("disabled", "true");
Related
Working in Google Web Toolkit (GWT) I am using a CellList to render the details of a list of Tariffs (using a CompositeCell to show a CheckBoxCell next to a custom cell of my own).
I want to filter the list by tariff length (12, 18, 24, 36 months etc). I would like to render a checkbox for each tariff length at the top of the list, and update the dataProvider as necessary when users uncheck and recheck a box.
I do not know in advance the set of tariff lengths, they will be extracted from the result set when the page is rendered. There could just be two (requiring two checkboxes), but possibly there could be 10 (requiring 10 checkboxes) - I only want to render a checkbox for each as needed.
So somehow I need to associate an int value with each checkbox, and then pass that int to a function that updates the list by removing all tariffs that match. I'm just not sure how to add the handler for the checkboxes and how to get the value for that particular box.
This is what I'm thinking:
// panel to hold boxes
private Panel contractLengthPanel = new HorizontalPanel();
textPanel2.add(contractLengthPanel);
// create a set of the terms, by looping the result set
Set<String> contractTerms = new HashSet<String>();
for(ElecTariff tariff : tariffs)
{
contractTerms.add(Integer.toString(tariff.getContractLength()));
}
// loop that set, creating a CheckBox for each value
for(String term : contractTerms)
{
CheckBox box = new CheckBox(term + " Months");
// set all boxes with the same name, and a unique id
box.getElement().setAttribute("name", "termBoxes");
box.getElement().setAttribute("id", "termBox" + term);
contractLengthPanel.add(box);
}
Now I'm not sure if I'm along the right lines here, but now I have each box as part of the same group (they have the same name) I would like to use that to add a handler that is called when a box is checked or unchecked, passing the box id (which contains the tariff length) to that function.
I hope this wasn't too confusingly written. Help appreciated.
There really is nothing like a "group of checkboxes" in HTML, and neither there is in GWT. There are kind of "groups of radiobuttons" though, but it's only about having their checked state mutually exclusive, it doesn't change anything to the way you work with them from code.
You have to listen to changes on each and every checkbox.
What you can do though is to use the same event handler for all your checkboxes; something like:
ValueChangeHandler<Boolean> handler = new ValueChangeHandler<Boolean>() {
#Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
CheckBox box = (CheckBox) event.getSource();
String id = box.getFormValue();
boolean checked = box.getValue();
…
}
};
(note: I used getFormValue() rather than getElement().getId(); I believe it's a better choice: it's specifically made to associate a value with the checkbox)
We have a form with few fields marked as readOnly.
The issue is that the user is able to focus or navigate to these readOnly fields using mouse or keyboard tab, and we want to disallow this.
One way of not allowing this is to mark all such fields as 'disabled'. But when marked disabled, then though fields can not be focussed, but then these disabled fields also do not get submitted to the server which is not what is expected.
Thus, how can we prevent a focus at readOnly fields?
PS: The reason behind disallowing focus at readOnly fields is to provide better navigation through keyboards, so that by using tab key user navigates or jumps across only those fields which he can edit and all readOnly fields get ignored.
You could add a listeners to the base Field class that listens for focus events then if the field is readOnly to focus the next component.
listeners: {
focus: function(field)
{
if (field.readOnly)
{
field.nextSibling().focus();
}
}
}
Just override getSubmitData method and assign some other property to let overridden method know you want to submit regardless (say, forceSubmit):
Ext.define('My.form.Field', {
override: 'Ext.form.field.Field',
getSubmitData: function() {
var me = this,
data = null;
if ( me.disabled && me.readOnly && me.forceSubmit ) {
data = {};
data[me.getName()] = '' + me.getValue();
}
else {
return me.callParent();
}
return data;
}
});
Then you can require this class in your code and set the fields you need to be disabled, readOnly and have forceSubmit:
my field = new Ext.form.field.Text({
disabled: true,
readOnly: true,
forceSubmit: true,
value: 'foo'
});
That should do the trick.
I am trying to create a ListBox using GWT. I am using UiBinder to create the field.
I would like to set a default text on the list box and when a user clicks on the box, it should show me the list items. Once again, if user has not selected any option, it should show me the default text again.
Any way to do this either using Uibinder or some ListBox methods?
If I understand correctly you want a value to show but when the user clicks on the list it disappears and shows you the list items?
As far as I know there is no option to that natively.
What you can do is add the first item to hold your default value.
You can do this grammatically by using addItem in code or using:
<g:Listbox>
<g:item value="-1">Default text</g:item>
</g:Listbox>
works with gwt 2.1+
The value can still be selected.
You can choose to ignore it or add an attribute "disabled" with value "disabled" to the option element:
listbox.getElement().getFirstChildElement().setAttribute("disabled" ,"disabled" )
hope it helps a bit :)
You can also use a renderer to control what is shown if 'Null' is selected.
(Inspired by: How do I add items to GWT ListBox in Uibinder .ui.xml template ?)
private class SimpleRenderer implements Renderer<T>{
private String emptyValue = "Select a value";
#Override
public String render(T val) {
if(val == null) {
return emptyValue;
}
return val.toString();
}
#Override
public void render(T val, Appendable appendable) throws IOException {
appendable.append(render(val));
}
public void setEmptyValue(String emptyValue) {
this.emptyValue = emptyValue;
}
}
I have a RichFaces component that I want to render after an Ajax call which sets a JavaScript variable to either true or false.
When the variable is false, I don't want the panel to render. Is there any way to input the result of this variable (or any JS function call) in the rendered attribute of a component?
Richfaces renders components on the server side. So you have to pass your
parameter to server side. There are some ways to achieve this.
Create a hidden input on the page and link it to a flag in your bean. Something like,
class YourBean {
private boolean visible = false;
//getter,setter
}
On the page,
<h:selectBooleanCheckbox id="hiddeninput" style="visibility:hidden"
value="#{yourBean.visible}"/>
<rich:component id="compid" rendered="#{yourBean.visible}" />
<a:commandButton onclick="document.getElementById('hiddeninput').checked=true"
reRender="compid"/>
Or create two methods which sets flag to true or false.
class YourBean {
private boolean visible = false;
public void makeInvisible() {
visible = false;
}
public void makeVisible() {
visible = true;
}
}
On the page,
<rich:component id="compid" rendered="#{yourBean.visible}" />
<a:commandButton action="#{yourBean.makeInvisible()}" reRender="compid"/>
Option 1:
You can show/hide using JavaScript/jQuery from oncomplete attribute on ajax request.
Option 2 (better): you change a boolean property value in backend action's method, and use its value in rendered attribute.
RichFaces reRender can take an EL expression:
reRender="#{bean.componentsToUpdate}"
So, another option, you can decide in runtime (based on input) whether to render a particular component.
I have to bind my editor widget objects in property sheet.So that i can the property of my widget from property view.
Please help me on this, if possible provide me some code snippets.
You have a good example in the Getting started with Properties
Using the Properties view is simple enough.
Since it shows properties for the selected object, the first step to using it is to make sure that the workbench selection service knows about the object selected in your view. There’s an entire Eclipse Corner article written on the subject of the selection service
public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
getSite().setSelectionProvider(viewer);
viewer.setInput(getViewSite());
}
Once you have your view contributing to the workbench selection, you need to make sure that the objects that your view is selecting contribute properties
(extract)
public class Person implements IPropertySource {
private String name;
private Object street;
private Object city;
public Person(String name) {
this.name = name;
this.street = "";
this.city = "";
}
public Object getEditableValue() {
return this;
}
public IPropertyDescriptor[] getPropertyDescriptors() {
return new IPropertyDescriptor[] {
new TextPropertyDescriptor("name", "Name"),
new TextPropertyDescriptor("street", "Street"),
new TextPropertyDescriptor("city", "City")
};
}
I indicated earlier that this solution is “not necessarily [the] most correct”. This is because, for this to work, my domain object needs to know about the very view-centric (and Eclipse-centric) notion of being a property source; in short, there is a tight-coupling between the model and view and this not a good thing™.
Using adapter is a better approach, as described in this article:
Person should implement IAdaptable.
See also this recent article on how to create a custom property view
how to hack the Properties View to listen only to a specific view.
The isImportant() method is the one which decides whether to create an IPage for the specific IWorkbenchPart or not.
The idea is to override that method and return false for all the workbenchPart that we are not interested in. Lets create the view first:
<view
class="com.eclipse_tips.views.CustomPropertiesView"
icon="icons/sample.gif"
id="com.eclipse-tips.views.customePropertiesView"
name="My Properties View">
</view>
The CustomPropertiesView should extend PropertySheet and override the isImportant():
public class CustomPropertiesView extends PropertySheet {
#Override
protected boolean isImportant(IWorkbenchPart part) {
if (part.getSite().getId().equals(IPageLayout.ID_PROJECT_EXPLORER))
return true;
return false;
}
}
In this case, I'm making the view only to respond to Project Explorer and ignore other views
According to this thread, the same principle should be valid for an Editor instead of a View.
The property sheet listens to the workbench page selection provider.
The selection provider depends on what viewer/editor is active.
Each editor/viewer provides their own selection provider to use when that editor/viewer is active.
This way the property sheet doesn't care who is active, it just listens to the selection provider.
That way depending upon the view, a different set of properties are displayed.
For example, the Navigator view provides IResource selections, so the property sheet then displays IResource properties when the Navigator is active.
The Workbench Selection mechanism is illustrated in this article
The ISelectionListener is a simple interface with just one method.
A typical implementation looks like this:
private ISelectionListener mylistener = new ISelectionListener() {
public void selectionChanged(IWorkbenchPart sourcepart, ISelection selection) {
if (sourcepart != MyView.this && // 1
selection instanceof IStructuredSelection) { // 2
doSomething(((IStructuredSelection) selection).toList()); // 3
}
}
};
Depending on your requirements your listener implementation probably needs to deal with the following issues as shown in the code snippet above:
In case we also provide selections (e.g. a view or editor) we should exclude our own selection events from processing. This avoids unexpected results when the user selects elements within our part (1).
Check whether we can handle this kind of selection (2).
Get the selected content from the selection and process it (3).