I got some JQuery code that hides elements on my page. However I would like to keep showing the visible element when a page_load event has appeared.
Im using cshtml(razor) code, and in there I have a IsPost call, and I was wondering if a call to the JQuery .hide was possible.
The JQuery code:
<script>
$().ready(function () {
$(".btn").click(function () {
$(".Hide").hide("fast");
$("#" + $(this).data('type')).show("fast");
});
});
</script>
The C# code:
if(IsPost)
{
if(Request["btn"] == "btn1")
{
// Do some code
}
if(Request["btn"] == "btn2")
{
// Do some other code
}
}
The html code:
<div id="button1" class="Hide">
<form action="" method="post">
<input type="submit" name="btn" value="btn1" />
</form>
</div>
<div id="button2" class="Hide">
<form action="" method="post">
<input type="submit" name="btn" value="btn2" />
</form>
</div>
The answer I finally used looks like this:
<script>
$().ready(function () {
$(".btn").click(function () {
$(".Hide").hide("fast");
$("#" + $(this).data('type')).show("fast");
});
#{
if(IsPost)
{
<text>
$("#btn1).show("fast");
</text>
}
}
});
</script>
Related
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.
I need to create a newsletter form in my footer, so I had to include it in my layout.
I have successfully created the form using:
<footer>
<form method="post" asp-controller="NewsletterSubscriptions" asp-action="Create" data-ajax="true" data-ajax-method="post" data-ajax-success="success" data-ajax-completed="completed">
<div class="newsletter" id="newsletter">
<div class="form-group">
<input type="text" id="FullName" name="FullName" data-provide="FullName" class="form-control" placeholder="name" autocomplete="off">
</div>
<div class="form-group">
<input type="email" id="Email" name="Email" data-provide="Email" class="form-control" placeholder="email" autocomplete="off">
</div>
</div>
<div class="newsletter-btn">
<input type="submit" value="ok" />
</div>
</form>
</footer>
And in Head:
<head>
<script src="#Url.Content("/lib/jquery-validation/dist/jquery.validate.js")"></script>
<script src="#Url.Content("/lib/jquery-validation/dist/additional-methods.js")"></script>
<script src="#Url.Content("/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js")"></script>
<script>
success = function () {
alert("Hi !");
};
</script>
<script>
completed = function (xhr) {
alert("Hi ${xhr.responseText}!");
};
</script>
</head>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("FullName,Email")] NewsletterSubscription newsletterSubscription)
{
if (ModelState.IsValid)
{
_context.Add(newsletterSubscription);
await _context.SaveChangesAsync();
return Redirect(Request.Headers["Referer"]+ "#newsletter");
}
else
return View(newsletterSubscription);
}
When I submit, page is refreshed, form is submitted successfully, user is redirected to same page footer area.
But success, or completed functions are not triggered. what am I doing wrong?
Write your form tag as follows:
<div id="success-message-container" class="alert alert-success text-center d-none">
<strong>Success!</strong> You have been subscribed successfully!
</div>
<div id="failure-message-container" class="alert alert-danger text-center d-none">
<strong>Failure!</strong> There is some problem with the service.Please try again.If the problem persists
please contract with system administrator!
</div>
<form id="newsLetterForm" method="post" asp-controller="NewsletterSubscriptions" asp-action="Create">
// Your form contents
</form>
Then in the JavaScript :
$(document).on("submit", "#newsLetterForm", function (event) {
event.preventDefault();
event.stopImmediatePropagation();
var formData = new FormData(this);
var url = this[0].action; // if this does not work then use '#Url.Action("Create","NewsletterSubscriptions")'
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function (response) {
if (response) {
document.getElementById("newsLetterForm").reset();
$("#newsLetterForm input,textarea").removeClass('valid');
$("#success-message-container").removeClass("d-none");
setTimeout(function () {
$("#success-message-container").addClass("d-none");
}, 5000);
}
},
error: function () {
$("#failure-message-container").removeClass("d-none");
setTimeout(function () {
$("#failure-message-container").addClass("d-none");
}, 5000);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Note: css classes I have used is from Bootstrap 4
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.
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>
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>