How to set input type date's default value to today?using ASP net core 7.0 - c#

<input type="date" id="ngaydk" value="01/02/2023">
<input type="date" id="ngaydk" value="01/02/2023">
or
ViewData["greeting2"] = "01/01/2023";
<input type="date" class="form-control" id="ngaydk" value=#ViewData["greeting2"]>
resual :
I want show value "01/02/2023" at load page but
not show value "01/02/2023" helpme!

Format for a date value is YYYY-MM-DD
<input type="date" value="2023-02-01">

I have an asp.net core web application and this is what I have in my index.cshtml
<div>
<label>date:</label>
<input type="date" id="ngaydk" />
<input type="date" id="ngaydk2" />
<input type="date" id="mydate" />
#Html.TextBox("date1", DateTime.Now.ToString("yyyy-MM-dd"), new { type = "date" })
</div>
<script>
document.getElementById("mydate").valueAsDate = new Date();
console.info(document.getElementById("mydate").value);
</script>
#section Scripts{
<script>
$(function () {
console.info("value is :" + $("#ngaydk2").val());
$("#ngaydk2").val('#DateTime.Now.ToString("yyyy-MM-dd")');
console.info("value is :" + $("#ngaydk2").val());
});
</script>
}

Related

Create a Condition For all non empty fields to be ReandOnly - ASP.NET Core 6.0 MVC

I am developing my first web application with ASP.NET Core 6, and I have a form that shows some fields that I already have information inside of my database.
The problem is: these fields needs to be read-only, because my user needs to considerate the information from my database. If is null, then he needs to insert a value.
Here is an example (consider the field with already set readonly). Most of fields will need this code:
<div class="form-group row">
<div class="col-3">
<label for="Renda Bruta">Associado Desde:</label>
<input type="text" class="form-control">
</div>
<div class="col-3">
<label for="Renda Liquida">Cota Capital</label>
<input type="text" class="form-control">
</div>
<div class="col-6" style="text-align:center">
<label for="ServidorPublico">IAP:</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Quantidade" value="#Html.DisplayFor(model => model.iAP.QuantidadeProduto)" ReadOnly="readonly"/>
<input type="text" class="form-control" placeholder="Produtos" value=""#Html.DisplayFor(model => model.iAP.Pro)" ReadOnly="readonly"/>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label for="Renda Bruta">Margem Contribuição</label>
<input type="text" class="form-control">
</div>
<div class="col-8" style="text-align:center">
<label for="ServidorPublico">Cheque Especial</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Dias de Utilização" />
<input type="text" class="form-control" placeholder="Valor Utilizado" />
<input type="text" class="form-control" placeholder="Valor Contratado" />
</div>
</div>
</div>
I already build the form, and put some fields readonly with ReadOnly="readonly", but is there a way to loop all fields and put readonly with a loop or I really need to write in all fields the code `ReadOnly="readonly" ? My form is really big
But is there a way to loop all fields and put readonly with a loop or
I really need to write in all fields the code `ReadOnly="readonly" ?
My form is really big
Yes, you can set that ReadOnly attribute based on the value of your textbox field.
In this scenario you have to consider two way, either you should consider your textbox name attribute or type="text" attribute. Upon these two very way we will be decided which textbox set to readonly which is not.
For [type='text'] Attribute:
When [type='text'] means we will check all the textbox type of text and check if the textbox have value and set the readonly attribute:
View:
<div class="form-group row">
<div class="col-3">
<label for="Renda Bruta">Associado Desde:</label>
<input type="text" name="Associado" class="form-control">
</div>
<div class="col-3">
<label for="Renda Liquida">Cota Capital</label>
<input type="text" name="Cota" class="form-control">
</div>
<div class="col-6" style="text-align:center">
<label for="ServidorPublico">IAP:</label>
<div class="input-group mb-3">
<input type="text" name="Quantidade" class="form-control" placeholder="Quantidade" value="Test Value" />
<input type="text" name="Produtos" class="form-control" placeholder="Produtos" value="Test Value Products" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label for="Renda Bruta">Margem Contribuição</label>
<input type="text" name="Margem" class="form-control">
</div>
<div class="col-8" style="text-align:center">
<label for="ServidorPublico">Cheque Especial</label>
<div class="input-group mb-3">
<input type="text" name="Dias" class="form-control" placeholder="Dias de Utilização" />
<input type="text" name="Utili" class="form-control" placeholder="Valor Utilizado" />
<input type="text" name="Contra" class="form-control" placeholder="Valor Contratado" />
</div>
</div>
</div>
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("input[type='text']").each(function (index, item) {
console.log(item);
if ($(item).val() != "") {
$(item).attr('readonly', true);
}
});
});
</script>
}
Note: When will will set readonly to a textbox which has value based on the text type then we have to consider like input[type='text']
For name Attribute:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("input").each(function (index, item) {
console.log(item);
if ($(item).val() != "") {
$(item).attr('readonly', true);
}
});
});
</script>
}
Note: Remember in this scenario, you need to set name property for your textbox to identify uniquely as you can see I have added name property
Output:
what I understand that you want to make the input field enterable when the value of it is null. this is done by javascript.
I suggest to make all input fields read only.
use javascript to test each field, if its value is null make it enterable.
for example:
<input type="text" id="text1" class="form-control" placeholder="Quantidade" value="#Html.DisplayFor(model => model.iAP.QuantidadeProduto)" ReadOnly="readonly"/>
<script>
window.onload = function() {
if (document.getElementById("text1").value.length == 0)
{
document.getElementById("text1").readOnly = false;
}}
</script>
so basically when the page is loading the script will check if the input is null or not and it will do the action.

How can I attach an action event to a date picker in ASP.NET?

I want to execute a method in the controller when I select a date. I have this:
<input class="form-control col-sm-5" asp-action="SetTimes" asp-for="Date" type="date" value="#DateTime.Today.ToString("dd-MM-yyyy")" />
The asp-action="SetTimes" was suggested by another student. I wanted it to call the method "SetTimes()" in the controller whenever I pick a date, but it doesn't work.
asp-action is invalid in the input datetype field. Instead, you can do this in the js onchange function.
<input class="form-control col-sm-5" onchange="SetTime(this.value)" asp-for="Date" type="date" value="#DateTime.Today.ToString("dd-MM-yyyy")" />
#section scripts{
<script>
function SetTime(value) {
window.location.href = "Controller/Action?Date=" + value;
}
</script>
}

ASP.NET Core HTML Helper is not setting Default Value for Date

I have a form where I want the date to default to today's date.
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<input asp-for="ThrDate" class="form-control" value="#DateTime.Now"
type="date" asp-format="{0:yyyy-MM-dd HH:mm}" />
<span asp-validation-for="ThrDate" class="text-danger"></span>
</div>
My research would suggest that this would work, but the value is not actually passing through. Oh, and I still want the date picker to work.
Thanks!
You can try the following code:
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<input asp-for="ThrDate" class="form-control" id="date_info" type="date" asp-format="{0:yyyy-MM-dd}" />
<span asp-validation-for="ThrDate" class="text-danger"></span>
</div>
#section Scripts{
<script>
$(document).ready(function () {
var time = new Date();
var day = ("0" + time.getDate()).slice(-2);
var month = ("0" + (time.getMonth() + 1)).slice(-2);
var today = time.getFullYear() + "-" + (month) + "-" + (day);
$('#date_info').val(today);
})
</script>
}
Result:
And if you want use datetimepicker,you can use following code:
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
<input class="form-control datetimepicker-input" asp-for="ThrDate" type="text" data-target="#datetimepicker1" />
<div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
#section Scripts{
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.1/js/tempusdominus-bootstrap-4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.1/css/tempusdominus-bootstrap-4.min.css" />
<script>
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY HH:mm',
defaultDate: new Date(),
});
</script>
}
Result:
And another post gives us the answer:
Set default input value Datetime.Now on create view MVC ASP.NET Core 2?
but it's in the comments, so I will detail here.
In the controller, in the GET, set the value of the model item, such like:
PostThr postThr = new PostThr { ThrDate = DateTime.Now };
return view(model);
once you do this, the value assigned in the controller passes to the view. No modification to the view is necessary.
Side note: I seem to now have trouble with the formatting of the value, but that's rich world problems, or another question.
Shout out to Stephen Muecke!

Worldpay integration issue in MVC

I am trying to implement worldpay payment method in my MVC project and trying to make a test payment but it shows me this error
You have completed or cancelled your payment.
You have cookies disabled. To complete your payment, enable
cookies by changing the privacy settings in your browser. Then
return to the merchant's site and resubmit your payment.
Your session at WorldPay has timed out. Please return to the
merchant's site and resubmit your payment.
Code that i am trying
<form action="https://secure-test.worldpay.com/wcc/purchase" method="post">
<input name="address1" type="hidden" value="10 Downing Street" />
<input name="amount" type="hidden" value="100.00" />
<input name="cartId" type="hidden" value="DAW" />
<input name="op-DPChoose-VISA^SSL" type="hidden" value="DAW" />
<input name="cardNoInput" type="hidden" value="4444333322221111" />
<input name="country" type="hidden" value="GB" />
<input name="currency" type="hidden" value="GBP" />
<input name="email" type="hidden" value="dave#gov.uk" />
<input name="instId" type="hidden" value="eca6aba9-16b2-4ad0-8019-1212bbb2f152" />
<input name="name" type="hidden" value="Prime Minister" />
<input name="postcode" type="hidden" value="SW1A 2AA" />
<input name="tel" type="hidden" value="020 7925 0918" />
<input name="testMode" type="hidden" value="100" />
<input name="town" type="hidden" value="London" />
<input name="cardCVV" type="hidden" value="1234" />
<input name="cardExp.month" type="hidden" value="1" />
<input name="cardExp.year" type="hidden" value="2017" />
<div class="form-group">
<button class="btn btn-success btn-lg" type="submit">WorldPay Test Checkout</button>
</div>
</form>
Try this for test Order placement through WorldPay
<form action="/complete" id="paymentForm" method="post">
<span id="paymentErrors"></span>
<div class="form-row">
<label>Name on Card</label>
<input data-worldpay="name" name="name" type="text" />
</div>
<div class="form-row">
<label>Card Number</label>
<input data-worldpay="number" size="20" type="text" />
</div>
<div class="form-row">
<label>CVC</label>
<input data-worldpay="cvc" size="4" type="text" />
</div>
<div class="form-row">
<label>Expiration (MM/YYYY)</label>
<input data-worldpay="exp-month" size="2" type="text" />
<label> / </label>
<input data-worldpay="exp-year" size="4" type="text" />
</div>
<input type="submit" value="Place Order" />
</form>
Then add this script in your view file
<script src="https://cdn.worldpay.com/v1/worldpay.js"></script>
<script type="text/javascript">
var form = document.getElementById('paymentForm');
Worldpay.useOwnForm({
'clientKey': 'Your_Client_Key',
'form': form,
'reusable': false,
'callback': function (status, response) {
document.getElementById('paymentErrors').innerHTML = '';
if (response.error) {
Worldpay.handleError(form, document.getElementById('paymentErrors'), response.error);
} else {
var token = response.token;
Worldpay.formBuilder(form, 'input', 'hidden', 'token', token);
console.log(token);
$.ajax({
url: "/Home/payment/",
data: { token: token },
success: function (data) {
},
dataType: "html",
type: "POST",
cache: false,
error: function () {
//Error Message
}
});
form.submit();
}
}
});
</script>
Now add this Order Placement code in your controller
public ActionResult payment(string token)
{
var restClient = new WorldpayRestClient("https://api.worldpay.com/v1", "Your_Service_Key");
var orderRequest = new OrderRequest()
{
token = token,
amount = 500,
currencyCode = CurrencyCode.GBP.ToString(),
name = "test name",
orderDescription = "Order description",
customerOrderCode = "Order code"
};
var address = new Address()
{
address1 = "123 House Road",
address2 = "A village",
city = "London",
countryCode = CountryCode.GB,
postalCode = "EC1 1AA"
};
orderRequest.billingAddress = address;
try
{
OrderResponse orderResponse = restClient.GetOrderService().Create(orderRequest);
Console.WriteLine("Order code: " + orderResponse.orderCode);
}
catch (WorldpayException e)
{
Console.WriteLine("Error code:" + e.apiError.customCode);
Console.WriteLine("Error description: " + e.apiError.description);
Console.WriteLine("Error message: " + e.apiError.message);
}
return Json(null, JsonRequestBehavior.AllowGet);
}

Jquery Validation for a single field

My form is
#using (Html.BeginForm("Create", "Account", FormMethod.Post, new { #class = "CreateUser" ,id="createform"}))
{
#Html.ValidationSummary();
<div class="field"><label>User Name*</label></div><input name="UserName" type="text" />
<div class="field"><label>Name</label></div><div class="field1"><input name="FirstName" type="text" placeholder="First Name"/><input name="Middlename" type="text" placeholder="Middle Name" /><input name="LastName" type="text" placeholder="Last Name" /></div>
<div class="field"><label>Email*</label></div><input name="Email" type="text" />
<div class="field"><label>Mobile*</label></div><div class="field2"><input name="CountryCode" type="text" placeholder="Country Code" /><input name="Mobile" type="text" placeholder="Mobile Number" /></div>
<div class="field"><label>Language</label></div><input name="Language" type="text" />
<div class="field"><label>Expiry Date*</label></div><input name="Expiry" type="text" id="datepicker" />
<input id="send" class="subbtn" type="submit" value="Create"/>
How can I validate only user name field using jQuery?
if your need required field validator, you can use something like this(JS):
<input name="UserName" type="text" id="UN"/>
var textBox = document.getElementById('UN');
if(textBox=='')
//your error message
It looks like you want make user name a mandatory field. If it is so you need to add following attribute to your user name input control:
<input name="UserName" type="text" data-val="true" data-val-required="User name field is required."/>
Also you need to configure unobtrusive validation here is the link how to do it: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
$(document).ready(function(){
$('#createform').submit(function(){
var user_name = $('input:first').val();
if(user_name == /*whatever you want to test*/){
//doesn't pass test
this.preventDefault();
alert("Username error");
} else {
this.submit();
}
});
});

Categories

Resources