action method not working on input in playframework2.0 - playframework-2.2

I have created a web application which should take input from website and display it on a new page. I notice that my code is not getting called at all.
Routes file - I call localhost:9000 first. test method in Data controller is called which displays an input box and a submit button. Problem is on clicking submit, nothing happens
GET /data controllers.Data.test
GET /data/post controllers.Data.post
Model - what I enter in input should get mapped to User object using a form and get displayed in new page
case class User (name:String)
Controller code
object Data extends Controller {
val userForm = Form((mapping("name"->text))(User.apply)(User.unapply))
//this gets called for url localhost:9000/data
def test = Action {
Ok(views.html.dataIndex(None))
}
//PROBLEM - this should get called on clicking submit button but it doesn't get called
def post = Action { implicit request =>
println("in post")
val u:User = userForm.bindFromRequest().get
Ok(views.html.dataIndex(Some(u)))
}
}
View
#(u:Option[User])
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
</head>
<body>
#u match {
case Some(user) => {
<h1> You entered </h1>
<ul id="hardcode-list" >
<li>#user.name</li>
</ul>
}
case None => {
<h1>Feed User Data</h1>
<form action="/data/post" method="get">
<input type="text" name="name"/>
<input type="button" name="send" value="Submit"/>
</form>
}
}
</body>
</html>
What am I doing wrong?

Found the mistake. The button type should be 'submit'

Related

How to set focus for InputRadio / InputRadioGroup in Blazor?

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.

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);
}

Navigating to different views without reloading entire page

I have a layout page that has one dropdown box. I created 3 views that will make use of this
layout. The value selected in the dropdown will be used in all 3 views created.
I have actionlinks used for navigation in the layout. Here is what I will like to achieve
Avoid reloading the entire page(layout) when I navigate from view to view since I want to keep
the dropdown value selected.
How can I achieve this such that it is only the content of the views that will be changing
when I navigate from page to page by clicking on the action links. The value of dropdown selected
must always remain the same unless changed by user
#model Company.Domain.Classes.Companyviewmodel
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
<div class="page">
#{
ViewBag.Title = "Project Status Maintenance";
}
<div id="MainContent1">
<div id="ProjID">
<label for="SelectProjID">Project:</label>
#Html.DropDownList("ddlprojects", Model.GetProjectInformationActive.ProjectsInfoSelectList, Model.GetProjectInformationActive.SelectedProject)
</div>
<ul>
<li class="pp1">#Html.ActionLink("Section1", "Index", "Home")</li>
<li class="pp2">#Html.ActionLink("Section2", "GetSection1Data", "Home")</li>
<li class="pp3">#Html.ActionLink("Section3", "GetSection2Data", "Home")</li>
</ul>
<hr class="divide" />
#RenderBody()
</div>
<footer>
<div class="ftrcontent">
<p>Got it !!</p>
</div>
</footer>
</div>
</body>
</html>
You can use ajax to do partial page loads. To start, give a css class to your links so that we can use those as our jQuery selectors when wiring up the ajax behavior.
#Html.ActionLink("Section1", "Index", "Home",null, new {#class="ajaxLink"})
#Html.ActionLink("Section2", "GetSection1Data", "Home", new {#class="ajaxLink"})
#Html.ActionLink("Section3", "GetSectionwData", "Home", new {#class="ajaxLink"})
Now you should have a container div in your page to which we will load the partial view content. May be your current view (index ?) , you can add a container view like this
<div id="pageContent"></div>
Now, let's listen to the click event on our links, get the content of the target page's via ajax and load to the container div. Assuming you have jQuery loaded to your page, we can use jQuery load() method.
$(function(){
//Load the first link's content on document ready
var firstLinkHref=$("a.ajaxLink").eq(0).attr("href");
$("#pageContent").load(firstLinkHref);
$("a.ajaxLink").click(function(e){
e.preventDefault();
$("#pageContent").load($(this).attr("href"));
});
});
Since we are loading partial page content to our placeholder div, we do not need to return the full markup(including layout) from your action methods, We just need to the partial view content. You may use the PartialView() method instead of View() method to achieve this.
public ActionResult GetSection1Data()
{
if(Request.IsAjaxRequest())
{
return PartialView();
}
return View();
}

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".

Add Dynamically Links to jQuery Mobile

I read a lot about how to add stuff dynamically in jquery mobile, but I couldn't figure out how to add links.
Currently my solution looks like this:
Add a new Page - with id (id="list-1")
Creating a Link for it (href="#list-1")
This solution works perfectly in static pages, but I want to do it dynamically. I have tried a lot with page() and stuff like that but nothing helped me.
My questions are:
How do I add dynamic links & pages?
Did I choose the right way to use ids & anchors (#list-1) as links or is there another solution for jquery mobile?
Let me know if you need more information
To add dynamic links, I have found the easiest way is to just have an event listener waiting for a click on those links. This event listener then saves any parameters you want to pass into the next page you are visiting. You pass the parameters from the list element to the event listener by just specifying parameters within each "li" element.
(create the HTML for a list dynamically & store it into list-1-html)
$("div#my-page div[data-role=content]").html(list-1-html);
$("div.list-1 ul").listview();
$("div.list-1 ul").listview('refresh');
Then your event listener would look something like:
$('#my-page').delegate('li', 'click', function() {
passedParameter = $(this).get(0).getAttribute('passed-parameter');
});
When jQuery Mobile loads your next page, you'll probably want to load this page dynamically and you'll have this passedParameter variable available to you. To load the page dynamically, just add a listener that waits for JQM to try to load the page:
$('[data-role=page]').live('pageshow',function(e, ui){
page_name = e.target.id;
if (page_name == 'my-page-2'){
(do something with passedParameter)
}
});
This is the workflow I use with jQuery Mobile and it has been working just fine. I'm guessing in future releases, though, that they'll build in some kind of support for passing dynamic parameters to pages.
Any new enhancement to the DOM should be done before the page initializes. But by default JQM automatically initializes the page once the page is load in browser.
Hence first you need to set autoInitializePage property to false and then call initializePage() method after the new page and links are add to the document. Hope this helps.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).bind("mobileinit", function(){
$.mobile.autoInitializePage = false;
});
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script>
$(document).ready(function() {
//add a link.
$("#page1 div[data-role='content']").append('Next Page');
//add a page.
$('body').append(' <div data-role="page" id="page2" data-title="next page"><header data-role="header" class="header"> <h5>Page 2</h5></header><div data-role="content"><h3>Good Morning...</h3>Back</div><footer data-role="footer" data-position="fixed"><h5>© All rights reserved</h5></footer></div>');
});
window.onload = function() {
$.mobile.initializePage();
};
</script>
</head>
<body>
<div data-role="page" id="page1">
<header data-role="header" class="header">
<h5>jQuery Mobile</h5>
</header>
<div data-role="content">
<form method="get" action="" data-transition="slideup">
<label for="email">Email:</label>
<input type="email" name="email" id="email" value=""/>
</form>
</div>
<footer data-role="footer" data-position="fixed"><h5>© All rights reserved</h5></footer>
</div>
</body>
</html>