Radio Button Toggle call C# Function - c#

i build this application:
CRUD Application with ASP.NET Core 3.0 & Entity Framework 3.0 Using Visual Studio 2019
Now i found a nice toggle(https://codepen.io/shaneheyns/pen/OPWGry):
i will only have the toggle like this code:
<div class="pricing-switcher">
<p class="fieldset">
<input type="radio" name="duration-1" value="monthly" id="monthly-1" checked>
<label for="monthly-1">Monthly</label>
<input type="radio" name="duration-1" value="yearly" id="yearly-1">
<label for="yearly-1">Yearly</label>
<span class="switch"></span>
</p>
</div>
everything works(i copied the .css style), but how can i execute a C# function if monthly is checked?
i searched a lot and tried alot but nothing worked.
the only things is a extra submit button.
but i will something like an Onchange event or something that called a C# Function in my Controller.
if i have a button i would code it like this:
<a asp-action="monthly">Test!!</a>
Can somebody please help me?
Thank you!
now i updated my Code like this:
#using (Html.BeginForm("test1", "Test"))
{
<div class="pricing-switcher">
<p class="fieldset">
<input type="radio" name="Isactive" value="test1" id="monthly-1"checked>
<label for="monthly-1">monthly</label>
<input type="radio" name="test1" value="test2" id="yearly-1">
<label for="yearly-1">yearly</label>
<span class="switch"></span>
</p>
</div>
and the .js Code:
$(document).ready(function () {
$("input[name='Isactive']").change(function () {
$(this).closest("form").submit();
});
});
now the function in Controller is like this:
public void Isactive()
{
Debug.WriteLine("test");
}
The Function was called thanks! But 2 problems:
The switch does not toggle
On click the site will redirect to IsActive the browserlink is https://localhost:44311/Test/Isactive
How to fix these?
Sorry i know C#, but html/js/css are new to me

The switch does not toggle
For the first question, You should keep the name of two radio button the same.
<div class="pricing-switcher">
<p class="fieldset">
<input type="radio" name="duration-1" value="test1" id="monthly-1"checked>
<label for="monthly-1">monthly</label>
<input type="radio" name="duration-1" value="test2" id="yearly-1">
<label for="yearly-1">yearly</label>
<span class="switch"></span>
</p>
</div>
On click the site will redirect to IsActive the browserlink is https://localhost:44311/Test/Isactive
For the second question, This is the default behavior for form submission, the form points to this url. If you want to stay at the current page, you can submit the form with ajax.

Related

Focus back on textbox after submitting using ASP.NET Core MVC

I am trying to introduce a dynamic search function in my project. I have created a search form in my view which submits on keyup but the issue that I'm not facing is that when the view reloads, the text box is no longer in focus and so the user needs to click back onto it which obviously isn't ideal.
My view is set up as follows:
<form id="searchForm" asp-action="Index" method="get">
<div class="row">
<div class="col-9">
<input type="text" id="fooSearch" name="searchString" value="#ViewData["currentFilter"]" class="form-control" />
</div>
<div class="col-3">
<div class="row">
<div class="col-6">
<input type="submit" value="Search" class="btn btn-outline-secondary form-control" />
</div>
<div class="col-6">
<a asp-action="Index" asp-route-recent="true" class="btn btn-outline-secondary form-control">Recent</a>
</div>
</div>
</div>
</div>
</form>
with the following JQuery script to submit on keyup
$(function () {
$('#fooSearch').keyup(function () {
$('#searchForm').submit();
});
});
</script>
Can anyone help me to retain focus on the search textbox when the DOM is loaded?
To give the focus back to the searchbar, you can use jQuery's focus(), e.g.:
$("#fooSearch").focus();
Now, where you place this depends on whether your form submit is synchronous (and makes the page reload) or asynchronous.
If the submit is asynchronous, then you can place this in your keyup event handler, right after the code that submits:
$('#fooSearch').keyup(function () {
$('#searchForm').submit();
$("#fooSearch").focus(); //focus back on the search bar
});
Otherwise, you will need to call focus() from an onload event:
$(document).ready(function() {
$("#fooSearch").focus();
});
In all cases, first load or reload (submit), the focus should be on the search textbox so I think that you can just focus the textbox on load.
$(function() { $("#fooSearch").focus();});
The problem you may encouter is that the cursor will not be in the end of the keywords. So I think that the best option here is to use Ajax to the update the results each time the user change the keywords. Maybe waiting a few seconds before each update is a good idea also.
If you are using html5 you can just add autofocus to your html tag something like:
<input type="text" id="fooSearch" autofocus ="autofocus" name="searchString" value="#ViewData["currentFilter"]" class="form-control" />

html button is activating asp validation in html input form - Why?

I'd want to ask why after clicking on my custom button that just appends text to div that's inside form, then it activates asp validation of that form?
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div id="append_area">
</div>
<button id="appendChild" onclick="addText()">add new thing</button>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
<script>
function addText()
{
var div = document.getElementById('append_area');
div.innerHTML += `test`;
}
</script>
Set your button type as button
<button type="button" id="appendChild" onclick="addText()">add new thing</button>
As described in W3C documentation, default type of the <button> element can vary across different browsers, so it is a good practice to always specify it explicitly.
In this case, the default value is submit, so by clicking the button you are inadvertently causing the submit action and hence also validation to be performed as well.
To fix this, just specify the button type explicitly as button:
<button type="button" />
You can also do this:
<script>
function addText()
{
var div = document.getElementById('append_area');
div.innerHTML += `test`;
return false;
}
</script>
then you can call in code onclick="return addText()"
When you submit a form to a CGI program that resides on the server, it is usually programmed to do its own check for errors. If it finds any it sends the page back to the reader who then has to re-enter some data, before submitting again. A JavaScript check is useful because it stops the form from being submitted if there is a problem, saving lots of time for your readers.
<button type="button" id="ChildForm" onclick="add()">add new </button>
The CGI script is still more reliable, as it always works regardless of whether JavaScript is enabled on the client-side or not; but having this extra safety barrier is a nice thing to have in place. It makes your page much more user-friendly and takes out the frustration of having to fill out the same form repeatedly. It's also very precise, as you can point out the exact field where there's a problem.

Simple Razor C# .Net form: Checkboxes and Session Variable settings

First, I want to explain I do not know any Razor or C#. I have a client that I build out high-fidelity prototyping for. Some of the elements are getting kind of advanced where JavaScript is not working for me anymore.
The Ask:
I have a modal that I trigger (using bootstrap), this modal has some checkboxes in a form. Each checkbox will trigger to turn on or turn off a session that will turn certain elements on or off on a series of 5-6 pages. Here I am just working with one of those sessions. I can duplicate once I figure this out. Any help will be greatly appreciated.
Code:
#{
if (Request.Form["fitscorechecked"] != null && Request.Form["fitscorechecked"] == "on") {
Session["fitscore"] = "on";
} else {
Session["fitscore"] = "off";
}
}
My Form:
<form method="post">
<div class="row">
<div class="col-sm-12 bottom5"><input type="checkbox" id="fitscorechecked" name="fitscorechecked" value="true"/> Show fit score during adjustment</div>
<div class="col-sm-12 bottom5"><input type="checkbox" id="Anonymous" name="Anonymous" value="true" /> Make contributors anonymous</div>
<div class="col-sm-12 bottom5" data-toggle="tooltip" data-html="true" title="<h5>Advanced Options</h5><h6>Will allow you to view related tasks, manually adjust patterns (power users only), and the ability to download responses.</h6>">
<input type="checkbox" id="Advanced" name="Advanced" value="true" /> Show advanced options</div>
</div>
<div class="prototype-btngroup-center">
<a class="btn btn-default prototype-btn-spacersm" data-dismiss="modal">Cancel</a>
<a class="btn btn-primary" type="submit" value="submit" href="#stepAlign6" data-toggle="tab" data-step="5" data-dismiss="modal">Begin Alignment</a>
</div>
</form>
<form>
I have never built a form in .net so I am really lost. I just need something very simple that does not use controllers. Much of this code is show and then redone based on the updates from the product team, so something that is simple and easy to adjust.

MVC Form Action Automatically Changed by Areas

In my main layout (root), I added search tools (a textbox and a button) to find the products.
_Layout.cs
<form action="#Url.Action("SearchProduct", "Product")" id="frmSearchProduct" method="get" class="form-inline text-right">
<input type="text" name="ProductName" placeholder="Enter Product Name" class="form-control" />
<button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-search"></i></button>
</form>
The search function works properly, but if I opened page in Areas and clicked the button, it doesn't work. The form action (url) is changed depend on the Areas.
http://localhost:49458/Error/NotFound?aspxerrorpath=/Workflow/Product/SearchProduct
There is no ProductController in Workflow Areas, so that it generates the error. How to solve this?
try with
#Url.Action("SearchProduct", "Product", new { area = string.Empty })

Form post to another page

I am fairly new to C# and asp.net and am having trouble showing something submitted in a form. The form element is a tag. The drop-down info is pulled from a data base and displays correctly. It's just getting it to post to another page after the form is submitted is where I am having the problem. Any help would be appreciated.
Contact.aspx:
<form action="Default.aspx" method="post" data-transition="pop">
<div data-role="fieldcontain">
<label for="topEmails">Business Entity ID:</label>
<select name="topEmails" id="topEmails" data-native-menu="false"
runat="server">
</select>
</div>
<input type="submit" data-iconpos="right" data-inline="true"
data-icon="plus" name="sendMessage" id="sendMessage" value="Send Info">
</form>
Contact.aspx.cs:
AdventureWorks2012DataContext db = new AdventureWorks2012DataContext();
var emails = (from b in db.EmailAddresses
select new { b.EmailAddressID, b.BusinessEntityID }).Take(20);
topEmails.DataTextField = "BusinessEntityID";
topEmails.DataValueField = "BusinessEntityID";
topEmails.DataSource = emails;
topEmails.DataBind();
Default.aspx.cs:
FormSuccessBID.InnerHtml = "Business Entity ID: " + Request.Form["topEmails"] + "";
Any ideas why this wouldn't be working?
Update:
Contact.aspx:
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h2 style="text-align: center;">Contact Kyle</h2>
<form action="Default.aspx" method="post" data-transition="pop">
<div data-role="fieldcontain">
<label for="userFName">First Name:</label>
<input type="text" name="firstName" id="uFName">
</div>
<div data-role="fieldcontain">
<label for="userLName">Last Name :</label>
<input type="text" name="lastName" id="uLName">
</div>
<div data-role="fieldcontain">
<label for="productsCategories">Products:</label>
<select name="productCategories" id="productCategories" data-native-menu="false" runat="server"></select>
</div>
<div data-role="fieldcontain">
<label for="topEmails">Business Entity ID:</label>
<select name="topEmails" id="topEmails" data-native-menu="false" runat="server"></select>
</div>
<input type="submit" data-iconpos="right" data-inline="true" data-icon="plus" name="sendMessage" id="sendMessage" value="Send Info">
</form>
</asp:Content>
You're missing "runat='server'" in your form definition.
In ASP.NET you're also allowed one form per page. Not sure from what you're posted if you're trying to put multiple forms on there, but if you are, it's not going to work.
I think all you need to do to accomplish what you want is have an ASP.NET button on the page, with the postbackURL set to the page you want to go to. (Of course, you need to do this in a server-side form)
I think you're mixing ASP.NET methods with other, different technologies. (From the look of it, you probably used classic ASP or PHP perhaps?)
If you can't use .NET for whatever reason, the ID/name of the field is not going to be what you're expecting. You need to inspect the form post and find its value - something along the lines of "clt00_somethingelse_topEmails". (Again, this is going to be a heck of a lot easier if you use the .NET way of doing things, but you may have a requirement not to)

Categories

Resources