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.
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'm building a web application using ASP.NET CORE 3.1. There is a data table(EvCode) that has two columns, EventCode (key field) and EventType. On the page that lets a user add a new event there are a number of fields. Among them is EventCode and EventType. When the EventCode is entered and the user exits the field, I want to trigger an event that queries the EvCode table using the the value in the EventCode field to select the EventType, then populate the the EventType field with the value.
If I add a button to the page, I can run the event handler. I need the event handler to run automatically when the value in the EventCode field is changed.
Any suggestions or ideas on how to do this are appreciated.
Fei Han - Thank you for your suggestions and code. I used a different project where I trying to accomplish the same thing. The only differences, rather than using EventCode I used FamilyCode, and rather than use EventType I used FamilyName. The handler (OnGetFamilyNameByCode) was never called.
I've included my code, maybe you can see what I've done wrong.`
<form method="get" >
<div class="border backgroundWhite">
<div class="form-group row">
<div class="col-2">
<label asp-for="PublisherFamilyVM.PubDataList.LastName"></label>
</div>
<div class="col-6">
<input asp-for="PublisherFamilyVM.PubDataList.LastName" class="form-control" />
</div>
<span asp-validation-for="PublisherFamilyVM.PubDataList.LastName" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="PublisherFamilyVM.PubDataList.FirstName"></label>
</div>
<div class="col-6">
<input asp-for="PublisherFamilyVM.PubDataList.FirstName" class="form-control" />
</div>
<span asp-validation-for="PublisherFamilyVM.PubDataList.FirstName" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
#Html.LabelFor(m => m.PublisherFamilyVM, "Family Code/Name:")
</div>
<div class="col-2">
<!-- <input asp-for="PublisherFamilyVM.PubDataList.FamilyCode" class="form-control" /> -->
<input id="input_family_code" class="form-control" type="text" value="" onblur="getfamilyname();" />
</div>
<div class="col-4">
<!-- <input asp-for="PublisherFamilyVM.FamilyList.FamilyName" class="form-control" /> -->
<input id="input_family_name" class="form-control" type="text" value="" />
</div>
<span asp-validation-for="PublisherFamilyVM.PubDataList.FamilyCode" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-6 offset-2">
<partial name="_CreateAndBackToListButton" />
</div>
</div>
</div>
</form>
#section Scripts{
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script>
function getfamilyname() {
var familycode = $("#input_family_code").val();
if (familycode != "") {
$.getJSON(`/eventinfo?handler=FamilyNameByCode&familycode=${familycode}`, function (data) {
//console.log(data);
$("#input_family_name").empty();
$("#input_family_name").val(data);
});
}
</script>
}
***** PageModel *****
public JsonResult OnGetFamilyNameByCode(string familycode)
{
//code logic here
//retrieve data from database based on famiycode
return new JsonResult(familycode);
}
When the EventCode is entered and the user exits the field, I want to trigger an event that queries the EvCode table using the the value in the EventCode field to select the EventType, then populate the the EventType field with the value.
To achieve above requirement, you can try to make AJAX request to handler method then dynamically populate value of EventType input field based on returned value in blur event of EventCode input field, like below.
<input id="input_event_code" type="text" value="" onblur="geteventtype();" />
<input id="input_event_type" type="text" value=""/>
JS code
function geteventtype() {
var eventcode = $("#input_event_code").val();
if (eventcode!="") {
$.getJSON(`/eventinfo?handler=EventTypeByCode&eventcode=${eventcode}`, function (data) {
//console.log(data);
$("#input_event_type").empty();
$("#input_event_type").val(data);
});
}
//...
}
handler method
public JsonResult OnGetEventTypeByCode(int eventcode)
{
//code logic here
//retrieve data from database based on eventcode
//...
return new JsonResult(eventtype);
}
Test Result
Update:
A 404 error does on the $.getJSON line of code indicating the url cannot be found. I replaced '/eventinfo?handler= FamilyNameByCode&familycode=${familycode}' - with - '/Create?handler = FamilyNameByCode&familycode=${familycode}' Do a need to add the folder or something else?
Please check if your Create model class look like below.
public class CreateModel : PageModel
{
//properties here
//...
public void OnGet()
{
}
public JsonResult OnGetFamilyNameByCode(int familycode)
{
//code logic here
//retrieve data from database based on eventcode
//...
return new JsonResult("FamilyName_Here");
}
}
I have a simple contact message form written in razor asp.net and c#. Whenever the form is submitted, I am able to render the server response with no issues but for some reason, all of the input fields are maintaining the same values.
Here is the partial view:
#using PublicWebsite.Models.Contact;
#model ContactFormViewModel
<form role="form" id="contactForm" data-toggle="validator" method="post" asp-controller="Contact" asp-action="SubmitMessage">
#if (!string.IsNullOrWhiteSpace(Model.ServerResponse))
{
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="alert #(Model.ServerResponseSuccess ? "alert-success" : "alert-danger")" role="alert">
#Model.ServerResponse
</div>
</div>
</div>
</div>
}
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="prepend-icon">
<input type="text" asp-for="#Model.Name" name="Name" class="form-control input-lg" placeholder="Your Full Name" maxlength="50" required>
<i class="nc-icon-outline users_single-03"></i>
</div>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div class="prepend-icon">
<input type="email" asp-for="#Model.Email" name="Email" class="form-control input-lg" placeholder="Email" maxlength="200" required />
<i class="nc-icon-outline ui-1_email-85"></i>
</div>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="prepend-icon">
<input type="tel" asp-for="#Model.Phone" name="Phone" class="form-control input-lg" placeholder="Phone Number" maxlength="25" required>
<i class="nc-icon-outline ui-2_phone"></i>
</div>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<select class="form-control" asp-for="#Model.ContactReason" name="ContactReason" data-container-class="input-lg" required style="height:46px !important">
<option value="">Choose a Reason</option>
<option value="Home Remediation">Home Remediation</option>
<option value="Commercial Remediation">Commercial Remediation</option>
<option value="Employment Opportunities">Inquire about employment oppotunities</option>
<option value="Other">Other</option>
</select>
</div>
<div class="col-md-6">
</div>
</div>
</div>
<div class="form-group">
<textarea asp-for="#Model.Message" class="form-control" rows="10" name="Message" placeholder="Message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="mysitekeyishere"></div>
<input type="hidden" name="RecaptchaResponse" value="" />
</div>
<button type="submit" id="form-submit" class="btn btn-primary btn-lg icon-left-effect"><i class="nc-icon-outline ui-1_email-85"></i><span>Send message</span></button>
<div id="msgSubmit" class="hidden"></div>
</form>
Here is a look at the viewmodel:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace PublicWebsite.Models.Contact
{
public class ContactFormViewModel
{
[StringLength(50)]
public string Name { get; set; } = "";
[StringLength(200)]
public string Email { get; set; } = "";
[StringLength(25)]
public string Phone { get; set; } = "";
[StringLength(50)]
public string ContactReason { get; set; } = "";
public string Message { get; set; } = "";
[StringLength(250)]
public string ServerResponse { get; set; } = "";
public bool ServerResponseSuccess { get; set; } = false;
}
}
Inside of the Contact Index CSHTML page for Contact, I render the partial view without any issues.
#section Scripts {
<script src="#validatorPath"></script>
<script type="text/javascript">
$(function () {
$(document).on('submit', '#contactForm', function (e) {
$form = $(this);
$url = $form.attr('action');
$.ajax({
type: "POST",
url: $url,
data: $form.serialize(), // serializes the form's elements.
success: function (data) {
loadFormData(data); //This works
resetCaptcha();
},
error: function (data) {
alert(data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
function loadFormData(data) {
$formContainer = $('.contact-form-container');
$formContainer.empty();
$formContainer.html(data);
console.log(data); //This reports back the same results
}
function resetCaptcha() {
//reset captcha
$('.g-recaptcha').empty();
$.getScript('#recaptchaUrl');
}
});
</script>
}
<div class="col-md-7 contact-form-container">
#{ await Html.RenderPartialAsync("_ContactForm", new ContactFormViewModel()); }
</div>
Everything renders properly. As seen in the screenshot below.
Once the items are filled out, the following sendmessage function is called as seen in the scripts section above.
[HttpPost]
public async Task<IActionResult> SubmitMessage(ContactFormViewModel contactForm)
{
var captchaResponse = Request.Form["g-recaptcha-response"].ToString();
if (string.IsNullOrWhiteSpace(captchaResponse))
{
contactForm.ServerResponse = _errorCaptchaMessageBlank;
}
else
{
if (await ValidCaptcha(captchaResponse))
{
try
{
await SendCustomerMessage(contactForm);
var customerName = contactForm.Name;
//This works
contactForm = new ContactFormViewModel
{
ServerResponse = String.Format(_successfulSendMessage, customerName.Split(' ')[0]),
ServerResponseSuccess = true
};
}
catch
{
contactForm.ServerResponse = _errorCaptchaMessageInvalid;
}
}
else
{
contactForm.ServerResponse = _errorCaptchaMessageInvalid;
}
}
//This works and I get the response back on the front end
return PartialView("_ContactForm", contactForm);
}
You can even see the message errors on a successful attempt to the server (i.e. the server response as shown in the HTML) and it keeps the user's info as it should so they don't have to re-enter the data as shown in the image below.
Now on success, notice in the code above I create a new Contact Form with cleared values and a success message. However, the same information stays filled in like below. I want the contact form to be cleared out.
I have attempted even just returning back a completely new view model but still have the same problem where all of the data is almost cached. In my console.log response from the server, I get a partial view result with the values pre-filled so I know it's not a browser issue. Even when I debug the CSHTML page, I only see the server response and the success = true, all other fields are blank.
Any help to figure out why the server is still returning a partial view result with the filled in data would be much appreciated.
You can add this to your success callback function:
$('#contactForm').find('input[type=text], textarea, select').val('');
It basically finds all input fields within the form and clears out their values.
Try to change your success callback function like below:
success: function () {
document.getElementById("contactForm").reset();
},
Clearing model state helped to resolve a similar problem when Partial method returned messed-up data:
public PartialViewResult OnPostData()
{
...
ViewData.ModelState.Clear();
return Partial("_ViewName", model);
}
I currently have a form that when submit is clicked the selected value should be shown in the textarea/box and initial page should remain open.
But the problem I'm currently having is when I click the submit button, I'm being taken from the initial page and the value is being displayed on a blank page.
So basically I have two issues. How do I prevent being taken to another page once submit is clicked? And how can I get the value to be displayed in the textarea? I'm new to MVC, so any help would be greatly appreciated.
View:
<script language="JavaScript">
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("Envs").value;
}
</script>
<form asp-controller="CyberArk" asp-action="CyberArk" method="post" role="form" onsubmit="return confirm('Do you really want to carry out this action?');" id="form1" style="display:none;">
<div id="accordion" role="tablist" aria-multiselectable="true">
#* Form 1 *#
<div class="card">
<div class="card-header" role="tab" id="headingTwo">
<h5 class="mb-0">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo" style="font-size:15px;">
Vault Status
</a>
</h5>
</div>
<div id="collapseTwo" class="collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="card-block">
<div class="form-group">
<div class="form-group">
<p> This script returns status of vault servers for the chosen environment. It is used to determine if any servers overlap in order to detect a split brain.</p>
</div>
#model PAM_Dashboard_Project.Models.Vaults
#Html.DropDownList("Envs", new SelectList(Enum.GetValues(typeof(Envs))), "Select Enivronment", new { #class = "form-control" })
<br>
<div>
<button type="submit" onclick="showInput();">Submit</button>
</div>
<br />
<textarea class="form-control" cols="20" id="ouput1" name="output1" rows="2"></textarea>
</div>
</div>
</div>
</div>
</div>
</form>
Model:
public class Vaults
{
public string Envs { get; set; }
}
public enum Envs
{
RTPprod,
OMA,
BG1,
BG2,
Cloud,
Workstation,
QA
}
Controller:
public class CyberArkController : Controller
{
public IActionResult CyberArk()
{
return View();
}
[HttpPost]
public string CyberArk(Vaults newVault)
{
string SelectedValue = newVault.Envs;
return (SelectedValue);
}
}
Update your event attribute to:
onclick="showInput(event);"
Update your showInput method to:
function showInput(e) {
e.preventDefault();
document.getElementById('display').innerHTML = document.getElementById("Envs").value;
}
Note: You don't have an element with the id display, so you need to fix that.
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>