Jquery Validation for a single field - c#

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();
}
});
});

Related

Passing model from get method to a post nulls the model

When I pass model to the view on the post method the ProductId and UserId get nulled.
[HttpGet]
public async Task<IActionResult> AddReview(int id)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var model = new AddReviewViewModel()
{
ProductId = id,
UserId = userId
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> AddReview(AddReviewViewModel addReviewViewModel)
{
if (!ModelState.IsValid)
{
return View(addReviewViewModel);
}
//...
}
Here is how I call the post method.
<div class="row">
<div class="col-sm-12 offset-lg-2 col-lg-8 offset-xl-3 col-xl-6">
<form asp-action="AddReview" method="post">
<div class="mb-3">
<label asp-for="#Model.Comment" class="form-label">Comment</label>
<input asp-for="#Model.Comment" class="form-control" aria-required="true" />
<span asp-validation-for="Comment" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="#Model.Rating" class="form-label">Rating</label>
<input asp-for="#Model.Rating" class="form-control" aria-required="true" />
<span asp-validation-for="Rating" class="text-danger"></span>
</div>
<div class="mb-3">
<input class="btn btn-primary" type="submit" value="Submit Review" />
</div>
</form>
</div>
</div>
I have done something like this while adding a new product but I haven't had any problem.
You have to return the data. It needs to make a round-trip. This is typically done with hidden input fields.
<input type="hidden" id="ProductId" name="ProductId" value="#Model.ProductId">
<input type="hidden" id="UserId" name="UserId" value="#Model.UserId">
Full example
<form asp-action="AddReview" method="post">
<input type="hidden" id="ProductId" name="ProductId" value="#Model.ProductId">
<input type="hidden" id="UserId" name="UserId" value="#Model.UserId">
<div class="mb-3">
<label asp-for="#Model.Comment" class="form-label">Comment</label>
<input asp-for="#Model.Comment" class="form-control" aria-required="true" />
<span asp-validation-for="Comment" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="#Model.Rating" class="form-label">Comment</label>
<input asp-for="#Model.Rating" class="form-control" aria-required="true" />
<span asp-validation-for="Rating" class="text-danger"></span>
</div>
<div class="mb-3">
<input class="btn btn-primary" type="submit" value="Submit Review" />
</div>
</form>
If your version supports taghelpers you can also write:
<input type="hidden" asp-for="ProductId">
<input type="hidden" asp-for="UserId">
Or using the HtmlHelper:
#Html.HiddenFor(m => m.ProductId)
#Html.HiddenFor(m => m.UserId)
In all cases, make sure you add this inside the form.

.NET core MVC Make input element conditionally Readonly

I am a new .NET programmer. I have the following input:
<input asp-for="FirstName"
id="FirstName"
class="form-control"
value="#Context.Request.Query["FirstName"]"
type="text"
readonly="readonly" />
If the textbox has data, I want the textbox to be readonly, if there is no data in the textbox, then the user can input data. Can anybody give advice?
If the textbox has data, I want the textbox to be readonly, if there
is no data in the textbox, then the user can input data. Can anybody
give advice?
According to your code and description, it seems that you want to set the textbox to be read-only based on the FirstName query string parameter. I suggest you could try to use the following code (use Razor syntax):
#model MVCDemo.Models.Customer
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
#{
var value = Context.Request.Query["FirstName"].ToString();
if (string.IsNullOrEmpty(value))
{
<input asp-for="FirstName" id="FirstName" class="form-control" value="#value" type="text" />
}
else
{
<input asp-for="FirstName" id="FirstName" class="form-control" value="#value" type="text" readonly />
}
}
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
The screenshot as below:
Besides, if you want to make the textbox read-only after entering some value, you could use JQuery to add or remove the readonly attribute on the textbox.
You can do something like this
#{
var firstname= Context.Request.Query["FirstName"];
}
<input asp-for="FirstName" id="FirstName" class="form-control"
value="#Context.Request.Query["FirstName"]" type="text"
readonly="#(Context.Request.Query["FirstName"]=="" ? "False" : "True")">

Get values from multiple inputs with the same name. c# .net

I have this html form:
<form method="post" action="/Record">
<input type="text" name="items[0][name]" value="Watch" />
<input type="text" name="items[0][model]" value="Ballon" />
<input type="text" name="items[1][name]" value="Shape" />
<input type="text" name="items[1][model]" value="Bleu" />
<input type="text" name="items[2][name]" value="Accessory" />
<input type="text" name="items[2][model]" value="Hublot" />
<input type="submit" value="SEND" />
</form>
I need to get the value of every item. i try something like this in c# .net
String[] myItems;
myItems = Request.Form.GetValues("items");
foreach (var singleItem in myItems)
{
WriteLine(singleItem.name);
WriteLine(singleItem.model);
WriteLine(singleItem["name"]);
WriteLine(singleItem["model"]);
}
i appreciate your advice
let try as below:
var myItems = Request.Form["items"];

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);
}

MVC Basic - how to get html button in URL

I'm new in MVC.
I have simple HTML website where I have two three inputs
input to write email adress
one checkbox
button
I have one HomeController which have on method
[HttpGet]
public ActionResult Index()
{
return View();
}
I want to generate method [HttpPost] after I click the button.
Now after I am click inputbutton in my Url I have just one change
Before click
http://localhost:52254/Home/Index
and after
http://localhost:52254/Home/Index?
There is a form
<form>
<div class="col-xs-3">
<input type="email" class="form-control" id="email" placeholder="Wpisz adres email">
</div>
<br />
<label class="checkbox-inline">
<input type="checkbox" />
</label>
<br />
<a href="/Controller/View">
<input type="submit" value="Sign" class="btn btn-primary"/>
</a>
</form>
Change The Code Like This
#using (Html.BeginForm())
{
<div class="col-xs-3">
<input type="email" class="form-control" id="email" placeholder="Wpisz adres email">
</div>
<br />
<label class="checkbox-inline">
<input type="checkbox" />
</label>
<br />
<a>
<input type="submit" value="Sign" class="btn btn-primary"/>
</a>
}

Categories

Resources