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.
Related
i get date from cshtml as [StartDate - EndDate]
and the date in data base is split as start date as field and end date
i want to get this date in controller and split them before saveChanges in data base
cshtml code :
<div>
<input type="text" value='#Model.StartDate - #Model.EndDate' class="form-control pull-right" id="reservationtime" >
</div>
and controller code :
public ActionResult Edit([Bind(Include = "PerformanceId,EventId,VenueId,Score,Name,Image,Description,StartDate,EndDate,Facebook,Website,Views,IsClosedBooking,IsVisible,IsFeatured,Deleted,CreatedOn,CreatedBy,ModifiedOn,ModifiedBy")] Performance performance)
{
if (ModelState.IsValid)
{
db.Entry(performance).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(performance);
}
Create two hidden fields, one with name StartDate and other with name EndDate and assign the values accordingly. These values will be available in the controller when you post the form.
<input type="hidden" name="StartDate" value="#Model.StartDate" />
<input type="hidden" name="EndDate" value="#Model.EndDate" />
i reach to my answer i will use the event of daterangepaker
when i click apply i will split the date
$('#daterange').daterangepicker();
$('#daterange').on('apply.daterangepicker', function(ev, picker) {
var date = document.getElementById("reservationtime").value;
var res = date.split("-");
document.getElementById("startDate").value = res[0];
document.getElementById("endDate").value = res[1];
});
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.
So i have a querystring where i save a search value from a input textbox. When i write, what i wish to search for and press enter, i get redirected and then i have the input from the search in the querystring. I want to populate a listview using the values from the querystring. But for some reason i dont get the query string value?
Here is how i try to get the value from the querystring:
if (Request.QueryString["txtSearchInput"] != null)
{
string input = Request.QueryString["txtSearchInput"].ToString();
SearchForItems(input);
}
And here i the URL that i try to get the querystring from:
http://localhost:46202/Users/AllProducts?ctl00%24txtSearchInput=213
in this example i have entered 213 as the search criteria.
And last here is the inputbox where i enter the values:
<input runat="server" id="txtSearchInput" name="search" placeholder="GTIN, Brand or Article nr" />
changed the input box to this:
<input name="search" placeholder="GTIN, Brand or Article nr" />
and the queryrequest to this:
if (Request.QueryString["search"] != null)
{
string input = Request.QueryString["search"].ToString();
SearchForItems(input);
}
now it works. As stuartd said, the id tag messed up the querystring.
I'm having difficulty writing a custom remote validator that will evaluate distinct pairs of fields from a list? The list has 2 fields that need to be validated: Description and Amount. This is my list.
#for (int i = 0; i < Model.MyList.Count(); i++)
{
#Html.TextBoxFor(m => m.MyList[i].Description)
#Html.TextBoxFor(m => m.MyList[i].Amount)
#Html.ValidationMessageFor(m => m.MyList[i].Description)
#Html.ValidationMessageFor(m => m.MyList[i].Amount)
}
The validation rules are as follows:
Amount must be zero or greater. It cannot be blank.
Description is required only when an amount is greater than zero.
When description is entered, the amount must be greater than zero.
I've seen (and implemented) solutions like these, but they don't address this type of scenario of evaluating multiple distinct pairs of fields that are in a list.
Multiple fields validation using Remote Validation
how to use multiple AdditionalFields in remote validation - asp.net mvc
This is in my model. And the validation rules for Amount work. But the custom remote validator (ValidateDescriptionAmountPair) for Description fails.
[Range(0, int.MaxValue, ErrorMessage = "Amount must be 0 or greater.")]
[Required(ErrorMessage = "Amount is required.", AllowEmptyStrings = false)]
public decimal Amount { get; set; }
[Remote("ValidateDescriptionAmountPair", "MyController", AdditionalFields = "Amount")]
public string Description { get; set; }
This is my custom validator.
[HttpGet]
public virtual JsonResult ValidateDescriptionAmountPair(string Description, string Amount)
{
bool isOkay = true;
string reasonItsInvalid = string.Empty;
// TODO: Add code to evaluate business rules, and change
// isOkay and reasonItsInvalid accordingly.
if (isOkay)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
return Json(reasonItsInvalid, JsonRequestBehavior.AllowGet);
}
}
I put a breakpoint in ValidateDescriptionAmountPair. This method gets called, but the Description and Amount values arrive as NULL rather than with expected values.
These are some markup examples for fields rendered in the view.
<input data-val="true" data-val-remote="'Description' is invalid." data-val-remote-additionalfields="*.Description,*.Amount" data-val-remote-url="/MyController/ValidateDescriptionAmountPair" id="MyList_0__Description" name="MyList[0].Description" type="text" value="Paid for this" aria-invalid="false">
<input class="form-control text-right" value="5000.00" data-val="true" data-val-number="The field Amount must be a number." data-val-range="Amount must be 0 or greater." data-val-range-max="2147483647" data-val-range-min="0" data-val-required="Amount is required." id="MyList_0__Amount" name="MyList[0].Amount" placeholder="Dollar Amount" style="width:100px;" type="text" aria-required="true" aria-invalid="false" aria-describedby="MyList_0__Amount-error">
<input data-val="true" data-val-remote="'Description' is invalid." data-val-remote-additionalfields="*.Description,*.Amount" data-val-remote-url="/MyController/ValidateDescriptionAmountPair" id="MyList_1__Description" name="MyList[1].Description" type="text" value="test" aria-invalid="false" aria-describedby="MyList_1__Description-error">
<input class="form-control text-right" value="10000.00" data-val="true" data-val-number="The field Amount must be a number." data-val-range="Amount must be 0 or greater." data-val-range-max="2147483647" data-val-range-min="0" data-val-required="Amount is required." id="MyList_1__Amount" name="MyList[1].Amount" placeholder="Dollar Amount" style="width:100px;" type="text" aria-required="true" aria-invalid="false" aria-describedby="MyList_1__Amount-error">
<input data-val="true" data-val-remote="'Description' is invalid." data-val-remote-additionalfields="*.Description,*.Amount" data-val-remote-url="/MyController/ValidateDescriptionAmountPair" id="MyList_2__Description" name="MyList[2].Description" type="text" value="Paid for that" aria-invalid="false">
<input class="form-control text-right" value="20000.00" data-val="true" data-val-number="The field Amount must be a number." data-val-range="Amount must be 0 or greater." data-val-range-max="2147483647" data-val-range-min="0" data-val-required="Amount is required." id="MyList_2__Amount" name="MyList[2].Amount" placeholder="Dollar Amount" style="width:100px;" type="text" aria-required="true" aria-invalid="false" aria-describedby="MyList_2__Amount-error">
What I think may be happening is that the names applied to list entries don't exactly match the "Description" and "Amount" parameter names in ValidateDescriptionAmountPair(), because they have indexes applied to the names. In other words, the field names are MyList[1].Description and MyList[1].Amount, but the ValidateDescriptionAmountPair() method is looking for Description and Amount. That's just a hunch which could be totally off base. If indeed that's why it fails, then what is the solution?
At any rate, I need to be able to implement the business rules noted above, and I would prefer to do this using an MVC data annotation or custom remote validation approach rather than hand-rolling some client-side jQuery to do this. Thanks for your help.
I could not achieve this in remote validation. But you achieve this using controller and #Html.ValidationSummary()
Add #Html.ValidationSummary() in view
#Html.ValidationSummary();
#for (int i = 0; i < Model.MyList.Count(); i++)
{
#Html.TextBoxFor(m => m.MyList[i].Description)
#Html.TextBoxFor(m => m.MyList[i].Amount)
#Html.ValidationMessageFor(m => m.MyList[i].Description)
#Html.ValidationMessageFor(m => m.MyList[i].Amount)
}
In Controller check the logic for distinct value and add the error message to the summary
[HttpPost]
public ActionResult MultipleValidation(List<MyList> model)
{
bool isOkay = true;
string reasonItsInvalid = string.Empty;
// TODO: Add code to evaluate business rules, and change
// isOkay and reasonItsInvalid accordingly.
if (!isOkay)
{
// Message to display in validation summary
ModelState.AddModelError("", "Duplicate Record");
}
return View("View", model);
}
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