Show a checkbox for true value - c#

I have a WebGrid that shows value from my table and an edit button. when a user clicks this button a pop up form or dialog form comes out and its populated with values from the same table I mentioned earlier.
I have managed to format date values and now interested in formatting the boolean value (true/false ) from my table to be displayed in a checkbox. At the moment its displayed as a textbox with value true or false.
Below is part of my code:
$('#dialog-form2-edit').dialog(
{
//dialog form code .. this is fine
$.getJSON('/Methods/GetCertificate/' + $(this).attr('id'), function (data)
{ var certificate = data;
$('#edit-paid').val(certificate.Paid);
$('#edit-mark').val(certificate.Mark);
var date = new Date(parseInt(certificate.MarkDate.substr(6)));
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
$('#edit-markdate').val(year + '-' + month + '-' + day);
$('#edit-markdate').datepicker({ dateFormat: 'yy-mm-dd' });
Below is part of my html
<div id="dialog-form2-edit" title="Edit Certificate">
<form id="edit-certificate-form" action="#Href("~/Methods/UpdateCertificate")">
<div class="row">
<span class="label"><label for="markdate">Mark Date :</label></span>
<input type="text" name="markdate" id="edit-markdate" size="20"/>
</div>
<div class="row">
<span class="label"><label for="mark">Mark :</label></span>
<input type=text" name="mark" id="edit-mark" size="15"/>
</div>
The value Mark and Paid are boolean. Now I intend to have the type changed to text and need help to format the boolean value to checkbox.

If you have a server-side bool value, you can use conditional attributes in Web Pages 2 to manage checkboxes. You provide the bool to the checked attribute of the checkbox using Razor:
#{ var myBool = true; }
<input type="checkbox" name="mark" id="mark" checked="#myBool" />
If the bool is true, checked="checked" is rendered. If it is false, the checked attribute is not rendered at all.

Use this code to display your boolean value in checkbox.
$.getJSON('/Methods/GetCertificate/' + $(this).attr('id'), function (data)
{
var certificate = data;
if(certificate.Pass == true){
$('#edit-pass').attr('checked', 'checked')}
else {$('#edit-pass').removeAttr('checked', 'checked')};
// your other json data
})
The removeAttr is necessary since I am using jquery-1.4.2.min.js. Tested and its working

Related

Update contactNumber in a form with specific pattern

I have profile page and I have the prefill the data if the data is there in database.I am getting data from an API call. That data conatains a phoneNumber field with pattern (852) 074-1012. Now when the details are prefilled. The user can able update the fields of his wish. When thw user updates the contactNumber field the didplay format has be like this(852) 074-1012. Here is my code and I am not able to display in that format while updating the phone. If we defaultValue then dynamic changes won't work. If I use value I am not able to erase the contactNumber to replace it with new one. Here is my code,
function profielPage()
{
const [contactNumber, setContactNumber] = useState();
function handleContactNumberChange(event) {
const {value} = event.target
console.log(event.target);
if (!value) {
setContactNumber(value);
return;
}
let formattedValue = value.replace(/[^\d]/g, '') //remove non-numeric characters
//console.log("formattedValue : "+formattedValue);
if(formattedValue.length>3){
formattedValue = `(${formattedValue.slice(0, 3)}) ${formattedValue.slice(3)}`;
//console.log("formattedValue in 1st if: "+formattedValue);
}
if(formattedValue.length>9){
formattedValue = `${formattedValue.slice(0, 9)}-${formattedValue.slice(9)}`;
// console.log("formattedValue in 2st if: "+formattedValue)
}
// console.log("formattedValue in after all if conditions: "+formattedValue)
setContactNumber(formattedValue);
}
const [contactNumber, setContactNumber] = useState();
return
<div className={css([InputWrapper, `height: 12px;`])}>
<label for="phone">Phone Number</label>
</div>
<div className={css([InputWrapper, `height: 60px;`])}>
<input
className={css([
Input({ invalid: invalidPassword }),
LoginInput
])}
style={!isPhoneNumberValid ? invalid : null}
type="text"
name="phone"
placeholder="Phone Number"
//value={profileState.profile === null ? contactNumber: profileState.profile.phoneNumber}
defaultValue={profileState.profile === null ? contactNumber: profileState.profile.phoneNumber}
onChange={handleContactNumberChange}
aria-label="phone"
required
/>
</div>
}
I tried to solve it whole day but I am unable to do it. Looks like an easy one but I don't know where I am going wrong.

Using MvcGrid.Net error on binding filters MVC

I`m using MvcGrid.Net
Here is my cshtml page
<div class="well">
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="Opprtunity ID" data-mvcgrid-type="filter" data-mvcgrid-option="opprtunityid" />
</div>
<div class="form-group">
<input class="form-control" placeholder="Cluster" data-mvcgrid-type="filter" data-mvcgrid-option="Cluster" />
</div>
<button type="button" class="btn btn-default" data-mvcgrid-apply-filter="click">Apply</button>
</div>
</div>
I have two simple search button. When I can try to bind them to the MVC grid confing file i can't see the value in the QueryOptions.
Here is my grid-options:
.WithRetrieveDataMethod((context) =>
{
var options = context.QueryOptions;
int totalRecords;
var repo = DependencyResolver.Current.GetService<General>();
string sortColumn = options.GetSortColumnData<string>();
var items = repo.GetData(out totalRecords,
options.GetFilterString("opprtunityid"),
options.GetFilterString("Cluster"),
//active,
options.GetLimitOffset(),
options.GetLimitRowcount(),
sortColumn, options.SortDirection == SortDirection.Dsc);
return new QueryResult<SourcedPartner>()
{
Items = items,
TotalRecords = totalRecords
}
options.GetFilterString("opprtunityid") here i have a null value.
Can someone explain me why?
When using MVCGrid.Net, you have to make sure that you set up the table definition in MVCGridConfig.cs .
Key elements to filtering are:
1) When declaring the column, you must make sure that you add the following code to the column definition -
.AddColumns(cols => {
cols.Add("opportunityid").WithVisibility(false)
.WithFiltering(true) // MUST have filtering enabled on column definion, otherwise it will not appear in QueryOptions
.WithValueExpression(i => i.OpportunityID);
cols.Add("Cluster").WithHeaderText("Cluster")
.WithFiltering(true)
.WithVisibility(false)
.WithAllowChangeVisibility(true)
.WithValueExpression(i => i.Cluster);
2) You must make sure to include filtering as part of your MVCGridBuilder construction -
MVCGridDefinitionTable.Add("Filtered", new MVCGridBuilder<SourcedPartner>()
.AddColumns(....)
.WithSorting(true, "MySortedColumnName")
.WithFiltering(true) // This lets the GridContext know that something will populate QueryOptions.Filters section
.WithRetrieveDataMethod((context) =>
{
var options = context.QueryOptions;
string opID = options.GetFilterString("opprtunityid");
string cluster = options.GetFilterString("Cluster");
.......
});
When you debug your code, the Filters portion of QueryOptions will be populated with your values from the input boxes. If there is no value, you will have a zero length string that you must check for.
The column needs to have filtering enabled. The builder must have filtering enabled. The column name must match the data-mvcgrid-option name.
When all of these things are set up, you should see the value from your inputs in the Filter section of the QueryOptions.
Know this is late, hope this helps.
Look in the URL to see what variable/s are being sent and set accordingly in options.GetFilterString(******).
Worked for me.

Set Jquery datepicker to previous value selected on modelstate error

We are using the JQuery UI datepicker on an MVC project to populate a hidden form field that forms part of our model. The problem we have is when a Modelstate error occurs and the user is returned back to the orginal form they submitted (with the values they selected pre-populated) the JQuery UI datepicker reverts to the current date. We need this to display the date that the user selected. How would we go about doing this?
HTML
<div class="col-md-2">
#Html.LabelFor(model => model.Departure_Date, new { #class = "control-label required" })
</div>
<div class="col-md-3">
<div id="datepicker" class="dateDeparture"></div>
#Html.HiddenFor(model => model.Departure_Date, new { id = "departureDate"})
</div>
Javascript
$(".dateDeparture").datepicker({
altField: "#departureDate",
defaultDate: setDate,
dateFormat: "mm/dd/yyyy"
});
function setDate(){
var date = $('#departureDate').value;
if(date == ""){
date = new Date();
}
return date;
}
As you can see above we try and get teh value of the hidden field and then use that to set the date on the datepicker but this does not work and we get the following error:
TypeError: i.getTime is not a function
http://localhost:49438/scripts/jquery-ui.min.js Line 8
Any help with this issue would be greatly appreciated.
defaultDate expects a string value, you're passing it a function.
You should try executing the function like:
$(".dateDeparture").datepicker({
altField: "#departureDate",
defaultDate: setDate(),
dateFormat: "mm/dd/yyyy"
});
function setDate(){
var date = $('#departureDate').value;
if(date == ""){
date = new Date();
}
return date;
}

Find Html Checkboxes

How can I find dynamically generated Html Checkboxes from C#.
Need to find them by id and mark them as checked.
This code generates the HTML first:
StringBuilder sbHtml = new StringBuilder("");
sbHtml.Append("<div class=\"checkboxBtn\">");
sbHtml.Append("<input type=\"checkbox\" runat=\"server\"
class=\"chkBx\" id=\"" +
Convert.ToString(someid) + "\" />");
sbHtml.Append("<label>Compare</label>");
sbHtml.Append("</div>");
and the rendered HTML is
<div class="checkboxBtn">
<span class="uncheked"></span>
<input type="checkbox" runat="server" class="chkBx" id="23"></input>
<label>Compare</label>
</div>
There are many such checkboxes and I would like to find them by IDs
string[] PhoneIds = {"11","23","43"};
foreach(string id in PhoneIds)
{
HtmlInputCheckBox cBox = form1.FindControl(id) as HtmlInputCheckBox;
if(cBox!=null)
{
//cb.checked = true;
}
}
The if condition always fails as if the checkboxes dont exist. What should be done here.
you are assigning only one number to your string-arrey PhoneIds:
string[] PhoneIds = ["11,23,43"];
instead you need to use:
string[] PhoneIds = {"11","23","43"};
Then you will find them.
Because otherwise you would assign one string to your array, and thisone would be 11,23,43 and as far as you have no checkbox with that string, the if-condition fails.
Also you should not use numbers as ID's, as you can check out in this answer, where it states that until HTML5
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
you must start with a letter. Maybe your browser doesn't support HTML5 ?
Element IDs in HTML must not start with a number. That may be why ASP.NET can't find it either. I would put a prefix on it, such as cbox11.
To fix the HTML:
StringBuilder sbHtml = new StringBuilder("");
sbHtml.Append("<div class=\"checkboxBtn\">");
sbHtml.Append("<input type=\"checkbox\" runat=\"server\"
class=\"chkBx\" id=\"cbox" +
Convert.ToString(someid) + "\" />");
sbHtml.Append("<label>Compare</label>");
sbHtml.Append("</div>");
And for the loop
string[] PhoneIds = {"11", "23", "43"};
foreach(string id in PhoneIds)
{
HtmlInputCheckBox cBox = form1.FindControl("cbox" + id) as HtmlInputCheckBox;
if(cBox!=null)
{
//cb.checked = true;
}
}
You don't need to check these in the code behind, it can be done in jQuery:
<div class="checkboxBtn">
<span class="uncheked"></span>
<input type="checkbox" runat="server" class="chkBx" id="23"></input>
<label>Compare</label>
</div>
<script type="text/javascript">
$(function(){
$('div.checkboxBtn input[type="checkbox"]').prop('checked', true);
});
</script>
This will check all child checkboxes of div.checkboxBtn.

Pass hidden ID when textbox is changed

I have multiple textboxes, every textbox has a related hidden field, the hidden field's ID is a concatenation of a string with the model's ID (ex: "FormState25")
How can I pass the ID of a hidden field when a textbox being changed? I'm using the following code to detect textbox change:
$("#body-content-container").on('change', 'input[type="text"]', function () {
$("#FormState").val('dirty');
});
You can add custom attributes to the textbox tag itself that includes the Id of the hidden field, for example:
In View
#Html.TextBoxFor(model => model.Name, new { HiddenFieldId = "FormState" + Model.Id })
This way when a textbox get changed you can get the Id of the hidden field you already use to store whatever you want, and then modify the javascript to handle that hidden field's Id, like this:
Javascript
$("#body-content-container").on('change', 'input[type="text"]', function () {
var hiddenId = $(this).attr("HiddenFieldId");
$("#" + hiddenId).val('dirty');
});
The javascript will get the HiddenFieldId attribute of the corresponding hidden field from the textbox and change it's value. Try this and let me know..
You can use this to reference the element on which the anonymous function is defined, e.g.:
$("#body-content-container").on('change', 'input[type="text"]', function () {
$("#FormState" + this.attr('id')).val('dirty');
});
try this:
$("input[type=text]").click(function(){
var hiddenId = "FormState" + $(this).attr("Id");
var hiddenField = $("#" + hiddenId);
hiddenField.val("dirty");
});
EDIT:
if your hidden field rendered just after your inputbox then you can do the following :
$("input[type=text]").click(function(){
var hiddenField = $(this).next();
hiddenField.val("dirty");
});
hope this could help.
Here's another trick which I've used in the past. Enclose the two related input fields in a div (or other) element. Then use the fact that the text field and the hidden field are siblings to select the correct hidden field. Perhaps something like this (NOTE: I have not tested this example):
<div id="someId">
<input type="hidden" value="unchanged" />
<input type="text" value="some data" />
</div>
<script type="text/javascript">
var hiddenInput = $('#someId input:first')
var textInput = $('#someId input:last')
textInput.on('change', function() {
hiddenInput.val('modified');
});
</script>

Categories