How to set focus for InputRadio / InputRadioGroup in Blazor? - asp.net-core

I want to set the focus on the InputRadioGroup but it appears it doesn't have the ElementReference attribute unlike the other Blazor built-in form components. Should I just extend the InputRadioGroup and add the ElementReference or is there another way to set focus on the InputRadio or InputRadioGroup?

You could refer to the sample below to focus on the InputRadio.
Vehicle.cs
namespace BlazorApp1.Model
{
public class Vehicle
{
public string Name { get; set; }
}
}
file1.js
window.jsfunction = { focusElement: function (id) { const element = document.getElementById(id); element.focus(); } }
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>BlazorApp1</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="BlazorApp1.styles.css" rel="stylesheet" />
<script src="file1.js"></script>
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
Index.razor
#inject IJSRuntime js
#page "/"
<div>
<h4> vehicle Selected - #vehicle.Name </h4>
<EditForm Model="vehicle">
<InputRadioGroup #bind-Value="vehicle.Name" >
#foreach (var option in rdOptions)
{
<InputRadio Value="option" id=#option #onfocus="alrt" /> #option <br />
}
</InputRadioGroup>
<br>
<input Id="idPassWord" Type="password" />
<button #onclick="clickOK">Set Focus</button>
</EditForm>
</div>
#code{
BlazorApp1.Model.Vehicle vehicle=new BlazorApp1.Model.Vehicle(){Name = "auto"};
List<string> rdOptions = new List<string> { "car", "bus", "auto" };
private async void clickOK()
{
await Focus("car");
}
private void alrt()
{
Console.WriteLine("Element focused");
}
public async Task Focus(string elementId)
{
await js.InvokeVoidAsync("jsfunction.focusElement", elementId);
}
}
Output:
In the above code example, I am generating the InputRadio on the page which has the OnFocus event. While we try to set the Focus on the InputRadio using the JS code. OnFocus event gets fired and displays the message in a browser console. This proves that InputRadio is getting focused.
Further, you could modify the code as per your own requirements.

After some investigation, seems like the ability to focus for InputRadio/InputRadioGroup was removed due to some prior issues. They now returned the focus after I raised the issue, and it will be included to .NET 7.

Related

I included Blazor component to my ASP.NET Core 6 MVC project but it doesn't work

It displays but doesn't work button click.
Index.cshtml:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.css">
</head>
<body>
<component type="typeof(ShiftsEditor)" render-mode="WebAssemblyPrerendered"/>
</body>
</html>
ShiftsEditor.razor (it is the test component):
#page "/ShiftsEditor"
<h3>ShiftsEditor</h3>
<p>#prgf</p>
<button #onclick="UpdateHeading">button</button>
#code {
public string prgf = "str";
public void UpdateHeading() => prgf = "content updated";
}
You can check if the JS you are referencing in _Layout.cshtml is <script src="_framework/blazor.server.js"></script> or
<script src="_framework/blazor.webassembly.js"></script>.
server.js needs to use render-mode="ServerPrerendered", and webassembly.js needs to use render-mode="WebAssemblyPrerendered".
Index.cshtml:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.css">
</head>
<body>
<component type="typeof(ShiftsEditor)" render-mode="ServerPrerendered"/>
</body>
</html>
Add#using Microsoft.AspNetCore.Components and #using Microsoft.AspNetCore.Components.Web in razor.
ShiftsEditor.razor:
#page "/ShiftsEditor"
#using Microsoft.AspNetCore.Components
#using Microsoft.AspNetCore.Components.Web;
<h3>ShiftsEditor</h3>
<p>#prgf</p>
<button #onclick="UpdateHeading">button</button>
#code {
public string prgf = "str";
public void UpdateHeading() => prgf = "content updated";
}
_Layout.cshtml:
<base href="~/" />
<script src="_framework/blazor.server.js"></script>
Program:
builder.Services.AddServerSideBlazor();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
}
Test Result:
Before click:
After click:

Bootstrap Alerts in Asp.net Core Razor Pages

How to configure bootstrap alerts in asp.net core razor pages.
<div class="alert alert-success">
<strong>Well done!</strong> You successfully read this important alert message.
</div>
As far as I know, if you want to show the alert, you could try to use jquery to achieve your requirement, you could add class in into the alert div. You could use ajax to call the razor page's onpost method and check the response if the response is true then you could alert success if not you could alert fail message.
More details, you could refer to below example codes:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
#{
Layout = null;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="alert alert-success alert-dismissible fade" id="buttonAlertSuccess">
<strong>Well done!</strong> You successfully read this important alert message.
</div>
<div class="alert alert-success alert-dismissible fade" id="buttonAlertFail">
<strong>False</strong> You failed read this important alert message.
</div>
<button class="btn btn-secondary" id="modalButton" type="submit">Button</button>
#Html.AntiForgeryToken()
<script>
$(function () {
$("#modalButton").click(function () {
$.ajax({
type: "post",
url: "index",
beforeSend: function (xhr) {
xhr.setRequestHeader("CSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
if (response == "True") {
$("#buttonAlertSuccess").addClass('in');
} else {
$("#buttonAlertFail").addClass('in');
}
}
});
})
});
</script>
Post method:
public ActionResult OnPost() {
return new JsonResult("True");
}
Notice:
If you want to use ajax call ,you should set the CSRF-TOKEN settings in the startup.cs ConfigureServices method like below:
services.AddAntiforgery(o => o.HeaderName = "CSRF-TOKEN");
Result:
Please find the complete code and try if it helps
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div id="alert_div" style="margin: 0 0.5%; -webkit-box-shadow: 3px 4px 6px #999;" class="alert-success">
<strong>Well done!</strong> You successfully read this important alert message.
</div>
</body>
</html>

How to make this ASP.NET Core Model Validation work on client-side?

In my ASP.NET Core 1.1.1 app the following Model Validation is not working. I think the issue is related to me not properly adding validation scripts in Main View below.
Scenario:
I click on a button on Main View that calls a partial view.
I enter all correct values, in partial view and submit the form (in partial view), the form successfully gets submitted and all the values are correctly entered into SQL server db.
I then intentionally enter a string, say, abc into the input box for price (that is of nullable type float) and submit the form. A client side error does NOT show up even (the javascript is enabled on my Chrome browser). Hence, Form gets submitted to the server where ModeState.IsValid, as expected, is false in the POST action method.
Question: Why client-side validation (as shown in step 3) above is not working and how we can make it work?
Note: All the css and javascripts were added and configured by default by VS2017 when the project was created. So I think scripts are all there and I may not be calling them correctly on the views - but that's just an assumption.
MyViewModel
public class MyViewModel
{
public int FY { get; set; }
public byte OrderType { get; set; }
public float? Price { get; set; }
....
}
Main View
#model MyProj.Models.MainViewModel
...
<div>
<button type="submit" name="submit"...>GO</button>
</div
#section scripts
{
<script>
$(document).ready(function () {
....
$('.tab-content').on('click', '.BtnGO', function (event) {
....
$.ajax({
url: '#Url.Action("SU_AddCustOrder", "MyContr")',
data: { ....},
contentType: 'application/json',
dataType: 'html',
type: 'GET',
cache: false,
success: function (data) {
if (BtnVal == 'AddOrderBtnGo')
$('#menuAP').html(data);
else if ....
error: function (....){
alert(...);
}
});
});
MyContrController:
[HttpGet]
public IActionResult AddCustOrder(int Order_id)
{
....
return PartialView("~/Views/PartialsV/MyPartialView.cshtml", myVM);
....
}
[HttpPost]
public IActionResult AddCustOrder(MyViewModel model)
{
....
if(ModelState.IsValid)
{
....
}
....
}
Partial View
....
<div class="form-group">
<label asp-for="Price"></label>
<div class="col-md-10">
<input asp-for="Price" class="form-control"></input>
<span asp-validation-for="Price" class="text-danger"></span>
</div>
</div>
....
<button type="submit" name="submit"...>Add Order</button>
UPDATE
_layout.cshtm file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - Test</title>
<environment names="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
#RenderSection("styles", required:false)
</head>
<body>
<header>
<div class="container navbar navbar-inverse navbar-fixed-top text-center">
</div>
<div class="container nav nav-pills" style="margin-top:4px;background-color:cornsilk;">
#await Component.InvokeAsync("Welcome")
</div>
</header>
<div class="container body-content">
#RenderBody()
<hr />
<footer class="text-center">
<a asp-controller="Misc" asp-action="AccessibilityStatement" class="text-center text-muted">Accessibility Statement</a>
</footer>
</div>
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
#RenderSection("scripts", required: false)
#RenderSection("css", required:false)
</body>
</html>
I see. If you go and open Shared folder inside Views folder you will find a file called _ValidationScriptsPartial.cshtml that contains the validation scripts.
Now the first thing to do is to add validation attributes such as [Required] to your view model.
Than in Main View add #{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } before <script>.
After you add the html of the partial view in this line $('#menuAP').html(data);, find the form and call $.validator.unobtrusive.parse() like the following
if (BtnVal == 'AddOrderBtnGo') {
$('#menuAP').html(data);
var $form = $('#menuAP').find('#your-form-id-here');
$.validator.unobtrusive.parse($form);
}

Button click to display a table from mysql in ibm mobile first

I am in process of learning so kindly help me to do how the retrieval of table from mysql in ibm mobile first by just clicking an button from my html page. I have tried but not working help please
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>vikdemodb</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<!--application UI goes here-->
<div id="header">
<h1>database Demo</h1>
</div>
<div id="wrapper">
<input type="button" id="databasecon" value="click me to get data from db" /><br />
</div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
My main.js
function wlCommonInit(){
$('#databasecon').click(loadSQLRecords);
}
function loadSQLRecords(){
var invocationData = {
adapter : 'vikadap',
procedure : 'getstudinfo',
parameters : []
};
WL.Client.invokeProcedure(invocationData,{
onSuccess : loadSQLQuerySuccess,
onFailure : loadSQLQueryFailure
});
}
function loadSQLQuerySuccess(result){
window.alert("success");
console.log("Retrieve success" + result);
console.log(result.invocationResult.resultSet);
}
function loadSQLQueryFailure(result){
WL.Logger.error("Retrieve failure");
}
You have a button in your HTML:
<input type="button" id="databasecon" value="click me to get data from db" />
You handle this button in wlCommonInit():
$('#databasecon').click(loadSQLRecords);
In loadSQLRecords() you call an adapter procedure to retrieve data from the database. If this operation succeeds then it calls the loadSQLQuerySuccess callback function.
It is this function that you are supposed to handle the display of the response from the backend (your database). But what are you doing? You only print to the console the response. You do not handle at all, displaying it in the application - in the HTML.
So in your HTML, you need to prepare a place holder that you will append the result into. For example: <table id="mytable"></table>
Then you need to populate the table with the data...
So in loadSQLQuerySuccess, you could for example do the following... this is where you need to learn HTML and JavaScript to accomplish what YOU want it to look like:
function loadFeedsSuccess(result) {
if (result.invocationResult.resultSet.length > 0)
displayFeeds(result.invocationResult.resultSet);
else
loadFeedsFailure();
}
function loadFeedsFailure() {
alert ("failure");
}
function displayFeeds(result) {
for (var i = 0; i < result.length; i++) {
$("#mytable").append("<tr><td>" + result[i].firstName + "</td></tr>");
$("#mytable").append("<tr><td>" + result[i].lastName + "</td></tr>");
}
}
Note that you need to create your own code in the for loop to make it look like how you want it to look, and of course append your own properties from the database, instead of "firstName" and "lastName".

How to update variables in .less file dynamically using AngularJS

I am very much new to AngularJS. I want to update the .less files variable dynamically. But didn't get how to access this .less file using AngularJS.
My code:
style.less
#bg-color: #484848;
.header{
background: #bg-color;
}
I want to update #bg-color: #484848; present in the style.less file to some value input by user. How can I get this using AngularJS.
You should run Less in browser to do this. If you load less.js in your HTML, the global less object come available, so you can use less.modifyVars() and less.refreshStyles() inside your angularJS code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example78-production</title>
<link rel="stylesheet/less" type="text/css" href="color.less" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.1/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.3.1/less.min.js"></script>
</head>
<body ng-app="submitExample">
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [];
$scope.text = 'orange';
$scope.submit = function() {
if ($scope.text) {
less.modifyVars({ color : $scope.text });
}
};
}]);
</script>
<h1>Colored text</h1>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
</body>
</html>
See: http://plnkr.co/5b1HTkneFXLMGVvXEG8j http://plnkr.co/edit/Z9tRY3Lol31PMnPUfxQi