client side validation in htmlhelper without Model Class - c#

I visited through different links but couldn't find desired answer. I am not using model for this view. Before sending data to server I want to check whether the text input is null or not.How can I validate it?
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<h2>Student Information</h2>
#using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
{
<label>First Name:</label>
<input type="text" class="form-control" name="firstname" id="f_name" />
<button type="submit" class="btn btn-success" >Insert</button>
}
</div>
<script>
$(function () {
$("#target".submit(function (event) {
event.preventDefault();
//return false;
})
})
</script>

Try this, I use empty string ('') instead of null since usually empty textbox are just empty string and not necessarily null.
<script>
$(function () {
$('button.btn').unbind();
$('button.btn').click(function () {
if($("#f_name").val() == ''){
return false;
}
return true;
})
})
</script>

If you dont want custom script for validating data on client side, you can use jquery.validate.js and jquery.validate.unobstrusive.js. This will work just like mvc validation rules(Actually this validation logic is generated by MVC itself on the view when client side validation is enabled).
Just add this three script file inside your page.
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>
Or you can select from your Script folder inside MVC application.
And Try to add following attribute in your Htmlelement for validation.
<div class="container">
<h2>Student Information</h2>
#using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
{
<label>First Name:</label>
<input data-val="true" data-val-required="First Name field is required." type="text" class="form-control" name="firstname" id="firstname" />
<span class="field-validation-valid" data-valmsg-for="firstname" data-valmsg-replace="true"></span>
<button type="submit" class="btn btn-success" >Insert</button>
}
</div>
This will work just like MVC validation inside your view.
You can get more information how to use JqueryValidate and jquery unobtrusive by clicking on this link : http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

You can get the value with a simple jQuery statement - $("#f_name").val() and then check if it is null $("#f_name").val() == null
So your complete javascript would be
<script>
$(function () {
$("#target".submit(function (event) {
event.preventDefault();
if($("#f_name").val() == null){
return false;
}
return true;
})
})
</script>

Related

Razor pages jQuery function validation issue

I have a form in Razor Pages .NET Core and inside this form I have a dropdown. This dropdown takes it's values (strings) from a jQuery function like this:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#StartDate").on("change", function () {
var time = $(this).val();
$("#select").empty();
$("#select").append("<option value=''>select </option>");
$.getJSON(`?handler=Time&time=${time}`, (data) => {
$.each(data, function (i, item) {
*$("#select").append("<option value='" + "'>" + item.hours + "</option>");*/
$("#select").append($("<option>").val(item.hours).text(item.hours));
});
});
});
});
</script>
<form method="post" id="myForm">
<div class="form-group">
<h6><label class="col-form-label">Time</label></h6>
<select id="select" asp-for="Time" class="form-control"></select>
<span class="text-danger" asp-validation-for="Time"></span>
</div>
</form>
Backend:
[Required(ErrorMessage = "Field cannot be empty!")]
[BindProperty]
public string Time { get;set; }
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
}
My issue is that after I submit my form, the ModelState.IsValid check always fails.
After some research, I found out that the reason is in my jQuery function because the added values are not validated.
I tried adding this line to my function, but it did not help:
$.validator.unobtrusive.parse("#myForm");
Right now, what it happens is that if I select a value from the dropdown, the ModelState won't be valid and returns the page
In my code:
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="StartDate" class="control-label"></label>
<input asp-for="StartDate" class="form-control" min="#DateTime.Now.ToString("yyyy-MM-ddThh:mm")" max="2050-06-01T00:00" />
<span asp-validation-for="StartDate" class="text-danger"></span>
</div>
<select id="select" asp-for="Time" class="form-control"></select>
<span class="text-danger" asp-validation-for="Time"></span>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#StartDate").on("change", function () {
var time = $(this).val();
$("#select").empty();
$("#select").append("<option value=''>select </option>");
$.getJSON(`?handler=Time&time=${time}`, (data) => {
$.each(data, function (i, item) {
*$("#select").append("<option value='" + "'>" + item.hours + "</option>");*/
$("#select").append($("<option>").val(item.hours).text(item.hours));
});
});
});
});
When I select a value from the dropdown,it will pass the validate,You can make an endpoint in your OnPost action.Below is my test,you can see which column failed the verification.

ASP.NET MVC Core - Preventing multiple form submission?

I'm designing a time clock web app, where on the main page where the user can clock in/out if they have a current activity record or not (from a SQL server database)
I have the following form:
<form asp-action="RegisterClockAction" asp-antiforgery="false" method="post">
<div class="form-group">
<input asp-for="ActiveFlag" type="hidden"/>
</div>
<div class="form-group row">
<div class="col-sm-5 offset-sm-1 center-column">
<button id="clock-in-btn" type="submit" class="btn clock-button" disabled>Clock In</button>
</div>
<div class="col-sm-5 center-column">
<button id="clock-out-btn" type="submit" class="btn clock-button" disabled>Clock Out</button>
</div>
</div>
</form>
Then I have the following JavaScript for this specific View
<script type="text/javascript">
$(function() {
const activeFlag = #Html.Raw(Json.Serialize(Model.ActiveFlag));
if (activeFlag) {
$("#clock-out-btn").prop("disabled", false);
} else {
$("#clock-in-btn").prop("disabled", false);
}
});
$("form").submit(function() {
if ($(this).valid()) {
$(this).find(":submit").attr("disabled", "disabled");
}
});
</script>
Now the form submit event does prevent from double submission, but is this the correct way I should be doing it?
Not sure if it's necessary to know, but all the controller POST action does, if the active flag is true then we find the record in the database, update it and commit the changes to mark inactive. Otherwise, we create a new record to append into the database. Then, I just redirect back to the Index view to rebuild the model.
you can fix this by using javascript
you should use event.preventDefault() so that the default action of the event will not be triggered again.
$("form").submit(function(e) { // 'e' <- add this line of code
e.preventDefault(); // <- add this line of code
if ($(this).valid()) {
$(this).find(":submit").attr("disabled", "disabled");
}
});

View component not rendering properly through AJAX

I've built a site where users can alter various types of data through multiple view components. When I call these view components on initial page load everything works fine. However when I try refreshing a view component through an ajax call, any lists in those view components repeat a single element multiple times, and my jquery functions stop working.
Here is my main view:
#model ContractModel
#using Portal.ViewComponents
#{
ViewData["Title"] = "Contract View";
}
...
<div id="ResultModel_Scope_Facplan">
#await Component.InvokeAsync("ContractPart", new { contractPartName = "Model_Scope_Facplan", projectName = Model.ProjectName })
</div>
My ajax:
#section Scripts {
<script>
$.ajaxSetup({ cache: false });
$(".PartialButton").click(function (event) {
event.preventDefault();
var ElementID = event.target.id.split("-");
var contractPart = ElementID[0];
var contractAction = ElementID[1];
var actionValue = ElementID[2];
console.log($("#Form" + contractPart + actionValue).serialize() + "&ProjectName=#(Model.ProjectName)&contractAction=" + contractAction);
console.log(ElementID);
$.ajax({
url: "#(Url.Action(""))/" + contractPart,
type: "POST",
data: $("#Form" + contractPart + actionValue).serialize()+"&ProjectName=#(Model.ProjectName)&contractAction=" + contractAction,
success: function (data) {
//Fill div with results
alert(data);
//debugger;
$("#Result" + contractPart).html(data);
},
error: failedSearch(contractPart)
});
});
function failedSearch(ElementID) {
// alert(ElementID + " failed!");
// $("#Result"+ElementID).html = "There was a problem in the search. Please try again later.";
}
</script>
}
My actual view component invoke is pretty simple (just sends the right data to the right view).
public IViewComponentResult Invoke(string contractPartName, string projectName)
{
return View(contractPartName, FindContractPart(contractPartName, projectName));
}
And the view component template:
#model IEnumerable<Model_Scope_Facplan>
#if (#Model != null)
{
<div class="row">
Care Provider Payer
</div>
#for (int i = 0; i < Model.Count(); i++)
{
<form id="FormModel_Scope_Facplan#(i)" action="">
<div class="form-horizontal">
<div class="col-md-3">
<input asp-for=#Model.ElementAt(i).CareProviderID class="form-control" />
</div>
<div class="col-md-3">
<input asp-for=#Model.ElementAt(i).PayerID class="form-control" />
</div>
<span class="glyphicon glyphicon-minus DeleteItem PartialButton" style="color:blue;" id="Model_Scope_Facplan-Delete-#(i)"></span>
</div>
</form>
<br/>
}
<form id="FormModel_Scope_Facplan#(Model.Count())" action="">
<div class="form-horizontal">
<div class="col-md-3">
<input name=CareProviderID class="form-control" />
</div>
<div class="col-md-3">
<input name=PayerID class="form-control" />
</div>
<span class="glyphicon glyphicon-plus AddItem PartialButton" style="color:blue;" id="Model_Scope_Facplan-Create-#(Model.Count())"></span>
</div>
</form>
}
The viewcomponent is returning the correct view template, and in debugging I can see that the ViewComponentResult.ViewData.Model includes the appropriate entries in the list. However the page updated after the ajax call includes only a single element over and over. What am I doing wrong?
Seems like my for loop in the view was breaking - I'm guessing the ElementAt(i) function didn't work after the ajax call for some reason. I ended up switching to a foreach loop and now everything works.

Embed Html `alert()` inside C# method call to display alert window MVC

I am trying to add Html code inside a #functions {} codeblock where if it matches some condition it will alert the user.
this is what I have so far, and I am getting the error CS0103: The name 'alert' does not exist in the current context
this is the code piece that is throwing the error.
#functions{
void doSomething(){
if(ViewBag.token != null){
#alert("#ViewBag.token");
}
}
}
Is there a way to embed alert() inside a C# code-block within .cshtml
this is the entire code which this function is in
#using System.Web.Mvc
#using System.Web.Mvc.Html
#using System
#using System.Web.UI
#model Dependency_Injection_MEF_MVC.Models.Payment
#section Scripts{
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
</script>
<script type="text/javascript">
$(function () {
var $form = $('#payment-form');
$form.submit(function (event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
ViewBag.token = token;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="Token">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
</script>
}
<div class="row">
<div class="col-md-12 form-column">
<div class="form-container">
<form asp-controller="home" asp-action="processpayment" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-group">
<h3>Membership Amount: USD XX</h3>
</div>
<div class="form-group">
<label for="cardNumber">Card Number</label>
<input class="form-control form-input" id="cardNumber" type="text" size="20" data-stripe="number" style= "width:250px;height:25px;font-size:120%">
</div>
<div class="form-group">
<label>Expiration (MM/YY)</label>
<div>
<input class="form-control form-input date-input" type="text" size="2" data-stripe="exp_month" style= "width:250px;height:25px;font-size:120%">
<input class="form-control form-input date-input" type="text" size="2" data-stripe="exp_year" style= "width:250px;height:25px;font-size:120%">
</div>
</div>
<div class="form-group">
<label for="cvc">CVC</label>
<input class="form-control form-input" id="cvc" type="text" size="4" data-stripe="cvc" style= "width:250px;height:25px;font-size:120%">
</div>
<input class="btn btn-default" onclick="doSomething()" id="submit" value="Submit Payment">
</form>
</div>
</div>
</div>
#functions{
void doSomething(){
if(ViewBag.token != null){
alert("#ViewBag.token");
}
}
}
Functions are intended to be completely server-side. But that script can be easily embeddable; if you move that to the page where you want it called, just do:
#if(ViewBag.token != null){
<script>
alert("#ViewBag.token");
</script>
}
And this will get rendered if the token exists. Functions aren't needed for this; this could be inside of a #helper though.

Html.EditorFor inside java script

I am learning ASP MVC and I try do form, and when you click the button on the form, I want to add some content to div in this form.
#using (Html.BeginForm())
{
<div>
<input type="button" value="Click to edit address" onclick="#String.Format("addAddress()")" />
<div id='divResult'>
Here I want to add new conntent after click button.
</div>
<div>
}
My Java Script function does't work:
<script type="text/javascript">
function addAddress() {
$('#divResult').replaceWith("#Html.EditorFor(m => m.User.HomeAddress)");
}
</script>
Can anyone help me? I want to fill my User (model.User) object and post filled to server, but Athe address you can fill only after click button, because it has a lot of field to be filled, but address is not necessary.
Try this:
#using (Html.BeginForm())
{
<div>
<input type="button" value="Click to edit address" onclick="addAddress()" />
<div id='divResult' hidden='hidden' >
#Html.EditorFor(m => m.User.HomeAddress)
</div>
</div>
}
-
<script type="text/javascript">
function addAddress() {
$('#divResult').show();
}
</script>

Categories

Resources