angular $resource save function is not mapping with dataannotation - asp.net

I am new to angular. And I am creating a practice project. I am following This tutorial.
Everything is working fine except when I try to put data annotations in my View Model the $resource.save method no more works. Without data annotations, it works fine.
Here is my code:
Home.html:
<!DOCTYPE html>
<html ng-app="movieModule">
<head>
<meta name="viewport" charset="UTF-8" content="width=device-width, initial-scale=1">
<title>Movie Sample</title>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/angular-resource.min.js"></script>
<script src="../Scripts/angular-route.min.js"></script>
<script src="../Scripts/jquery-2.1.1.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<script src="../Scripts/movie-module.js"></script>
<script src="../Scripts/Category/category-controller.js"></script>
<script type="text/javascript">
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(e.target).attr("href") // activated tab
});
</script>
</head>
<body>
<div class="container">
<div class="container-fluid">
<div class="well">
<ul class="nav nav-pills">
<li role="presentation" class="active">Home</li>
<li role="presentation">Movies</li>
<li role="presentation">Categories</li>
<li role="presentation">Artists</li>
</ul>
</div>
</div>
<div class="container-fluid">
<div ng-view="">
</div>
</div>
</div>
</body>
</html>
Categories.html:
<div>
<a href="create-category.html" class="btn btn-primary">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</a>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Categories</div>
<!-- Table -->
<table class="table">
<tr>
<th>ID
</th>
<th>Name
</th>
<th>Description
</th>
</tr>
<tr data-ng-repeat="category in categories">
<td>{{ category.id }}
</td>
<td>{{ category.name }}
</td>
<td>{{ category.description }}
</td>
</tr>
</table>
</div>
create-category.html
<div class="row">
<div class="col-md-12">
<h3>Create Category
</h3>
</div>
</div>
<!--<div class="row">-->
<div class="col-md-12">
<div class="form-group">
<label for="id">Id:</label>
<input type="text" ng-model="category.Id" class="form-control">
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" ng-model="category.Name" class="form-control">
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" ng-model="category.Description" class="form-control">
</div>
<button type="submit" class="btn btn-primary" ng-click="save(category)">Create Category</button>
</div>
movieModule.js
var movieModule = angular.module('movieModule', ['ngRoute', 'ngResource']);
movieModule.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/templates/categories.html', { templateUrl: '/templates/categories.html', controller: 'categoryController' }).
when('/templates/create-category.html', { templateUrl: '/templates/create-category.html', controller: 'categoryController' });
$locationProvider.html5Mode(true);
});
category-controller.js
movieModule.controller('categoryController', function ($scope, $resource, $location) {
$scope.categories = $resource('/api/Category').query();
$scope.save = function (category) {
$scope.errors = [];
$resource('/api/Category').save(category).$promise.then(
function () { $location.url('templates/categories.html'); },
function (response) {
$scope.errors = response.data;
});
}
});
CategoryVM.cs
public class CategoryVM
{
[Required(ErrorMessage="Is is required.")]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
The problem is [Required(ErrorMessage="Is is required.")]. Everything works fine without [Required(ErrorMessage="Is is required.")]but the moment I put [Required(ErrorMessage="Is is required.")] it starts giving error:
Here is the snapshot of the error:

Try not to put the [Required] attribute on the Id.
It should work if you put data annotations on your other properties.
[Required] to a value type (int) will cause a 500 error
(string is not a value type)

Related

Pass input with route id to controller method together

I want to create input with game amount. User will write how many copy of concrete game wants to buy. Then two parameters will pass to AddToCart method. First will be gameId like below (it works well) and user amount input. How to pass these two values together into controller method?
View:
#model IEnumerable
<link rel="stylesheet" href="~/css/productcards.css">
<div class="container">
<div class="row">
#foreach (var game in Model)
{
<div class="col-md-3">
<div class="product-grid">
<div class="product-image">
<a asp-controller="Game" asp-action="ShowDetails" asp-route-productId=#game.GameId>
<img class="pic-1" src="~/images/#game.ImagePath">
</a>
</div>
<div class="product-content">
<h3 class="title">
<a asp-controller="Game" asp-action="ShowDetails" asp-route-productId=#game.GameId>#game.Title</a>
</h3>
<div class="price">#game.Price.ToString() zł</div>
<a asp-controller="Cart" asp-action="AddToCart" asp-route-gameId="#game.GameId" class="btn btn-primary"><i class="fa fa-cart-plus"></i> KUP</a>
</div>
</div>
</div>
}
</div>
</div>
Controller:
public RedirectToActionResult AddToCart(int gameId)
{
var selectedGame = _appDbContext.Games.FirstOrDefault(x => x.GameId == gameId);
if(selectedGame != null)
{
_cart.AddToCart(selectedGame, 1);
}
return RedirectToAction("Index");
}
Change your view like below:
#foreach (var game in Model)
{
<form method="post">
<div class="col-md-3">
<div class="product-grid">
<div class="product-content">
<h3 class="title">
<a asp-controller="Game" asp-action="ShowDetails" asp-route-productId=#game.GameId>#game.Title</a>
</h3>
<div class="price">#game.Price.ToString() zł</div>
<div class="amount"><input name="amount" type="number" /></div> #*add this line*#
</div>
</div>
</div>
<div class="col-md-3">
#*change <a> to <input> and add a <form>*#
<input type="submit" asp-route-gameId="#game.GameId" asp-controller="Cart" asp-action="AddToCart" class="btn btn-primary" value="KUP"/>
</div>
</form>
}
Action:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddToCart(int gameId,int amount)
{
//do your stuff...
}
Result:

How to separate 2 POST and 2 GET method in 1 controller class in spring mvc

i am developing web app that have a transaction for buying a product and that transaction required a customer data. so in that transaction form, i add a modal form for user to add a new customer data.
here currently it's look like :
link to open the add new customer modal form
modal form to add customer
And here my full controller class :
#Controller
public class InvoiceProductController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private MsEmployeeService msEmployeeService;
#Autowired
private MsCustomerService msCustomerService;
#Autowired
CustomerFormValidator customerFormValidator;
#Autowired
private MsLocationService msLocationService;
#Autowired
private MsReligionService msReligionService;
// Set a form validator
#InitBinder("msCustomer")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(customerFormValidator);
}
#RequestMapping(value = "/trproduct", method = RequestMethod.GET)
public ModelAndView trproduct(Locale locale, HttpSession session) {
ModelAndView mav = new ModelAndView("entryinvoiceproduct");
MsUser loggedInUser = (MsUser) session.getAttribute("loggedInUser");
List<MsEmployee> msEmployee = msEmployeeService.findEmployeeByJobsAndLocation("BEAUTY CONSULTANT",
(short) loggedInUser.getMsLocation().getId());
List<MsCustomer> msCustomer = msCustomerService.findAll();
mav.addObject("listCustomer", msCustomer);
mav.addObject("beautyConsultant", msEmployee);
mav.addObject("defaultLocation", loggedInUser);
return mav;
}
#RequestMapping(value = "/trproduct", method = RequestMethod.POST)
public String saveCustomer(#ModelAttribute("customerForm") #Validated MsCustomer msCustomer, BindingResult result,
Model model, final RedirectAttributes redirectAttributes) {
logger.debug("saveOrUpdateUser() : {}", msCustomer);
if (result.hasErrors()) {
populateDefaultModel(model);
return "/trproduct";
} else {
// Add message to flash scope
redirectAttributes.addFlashAttribute("css", "success");
if (msCustomer.isNew()) {
redirectAttributes.addFlashAttribute("msg", "User added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "User updated successfully!");
}
msCustomerService.persist(msCustomer);
// POST/REDIRECT/GET
return "/trproduct";
// POST/FORWARD/GET
// return "user/list";
}
}
// show add customer form
#RequestMapping( method = RequestMethod.GET)
public String showAddCustomerForm(Model model, HttpSession session) {
logger.debug("showAddCustomerForm()");
MsCustomer msCustomer = new MsCustomer();
MsUser loggedInUser = (MsUser) session.getAttribute("loggedInUser");
msCustomer.setUpdateUserId(loggedInUser.getId());
msCustomer.getMsLocation().setId(loggedInUser.getMsLocation().getId());
model.addAttribute("customerForm", msCustomer);
populateDefaultModel(model);
return "";
}
private void populateDefaultModel(Model model) {
List<MsLocation> msLocation = msLocationService.findAll();
model.addAttribute("locationList", msLocation);
List<MsReligion> msReligion = msReligionService.findAll();
model.addAttribute("religionList", msReligion);
}
}
and here my jsp, that calling the modal form in it :
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- CSS -->
<link href='<c:url value="/resources/datatables/datatables.css" />'
rel="stylesheet">
<script src="<c:url value="/resources/datatables/datatables.js" />"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#invoicedtls').DataTable({
"pageLength" : 8,
"lengthMenu" : [ 8, 16, 32, 64, 100 ],
select : true
});
$('#invoicepayments').DataTable({
"pageLength" : 8,
"lengthMenu" : [ 8, 16, 32, 64, 100 ],
select : true
});
$('#existingcustomer').DataTable({
"pageLength" : 8,
"lengthMenu" : [ 8, 16, 32, 64, 100 ],
select : true
});
// $("body").on("click", ".use-address", function() {
// var id = $(this).closest("tr").find(".custid").text();
// var name = $(this).closest("tr").find(".custname").text();
// alert(id + " , " + name);
// });
});
</script>
<div class="panel panel-default">
<div class="panel-heading">
<h4>Invoice Header</h4>
</div>
<div class="panel-body">
<form role="form">
<div class="col-lg-4">
<label>Customer :</label>
<div class="input-group">
<input type="text" class="form-control text-uppercase">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle"
data-toggle="dropdown">
Customer <span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right">
<li><a data-toggle="modal" data-target="#modalNewCustomer">New</a></li>
<li><a data-toggle="modal"
data-target="#modalExistingCustomer">Existing</a></li>
</ul>
</div>
<!-- /btn-group -->
</div>
<!-- /input-group -->
</div>
<div class="col-lg-3">
<label>Beauty Consultant :</label> <select id="disabledSelect"
class="form-control">
<option value="-1">Select a Beauty Consultant</option>
<c:forEach items="${beautyConsultant}" var="bc">
<option value="${bc.id}">${bc.name}</option>
</c:forEach>
</select>
</div>
</form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<div class="form-group pull-right">
<button class="btn btn-primary pull-right">Add New Product</button>
</div>
<h4>Product List</h4>
</div>
<div class="panel-body">
<!-- <table class="table table-striped table-hover"> -->
<table id="invoicedtls" class="display highlight">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Qty</th>
<th>Discount Value</th>
<th>Discount Percent</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<div class="form-group pull-right">
<button class="btn btn-primary pull-right">Add New Payment</button>
</div>
<h4>Payment List</h4>
</div>
<div class="panel-body">
<!-- <table class="table table-striped table-hover"> -->
<table id="invoicepayments" class="display highlight">
<thead>
<tr>
<th>Pay With</th>
<th>Bank Name</th>
<th>Cardholder Name</th>
<th>Card No</th>
<th>Card Expired</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- Modal Existing Customer -->
<div class="modal fade" id="modalExistingCustomer" tabindex="-1"
role="dialog" aria-labelledby="modalExistingCustomerLabel">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="modalExistingCustomerLabel">Select
Existing Customer</h4>
</div>
<div class="modal-body">
<!-- <table class="table table-striped table-hover"> -->
<table id="existingcustomer" class="display compact">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Sex</th>
<th>Origin</th>
<th>Religion</th>
<th>Option</th>
</tr>
</thead>
<tbody>
<c:forEach var="customer" items="${listCustomer}">
<tr>
<td class="custid">${customer.id}</td>
<td class="custname">${customer.firstName}</td>
<td>${customer.sex}</td>
<td>${customer.msLocation.name}</td>
<td>${customer.msReligion.name}</td>
<td>
<button class="btn btn-link btn-xs use-address">Use</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Select
Customer</button>
</div>
</div>
</div>
</div>
<!-- Modal New Customer -->
<div class="modal fade" id="modalNewCustomer" tabindex="-1"
role="dialog" aria-labelledby="modalNewCustomerLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="modalNewCustomerLabel">Entry New
Customer</h4>
</div>
<div class="modal-body">
<form id="newCustomer" role="form" action="/admin/users/update" method="post">
<input id="id" name="id" placeholder="Id" value="0" type="hidden"
value="0" />
<div class="form-group">
<label for="firstName">First Name:</label> <input id="firstName"
name="firstName" placeholder="First Name" class="form-control"
type="text" value="" />
</div>
<div class="form-group">
<label for="lastName">Last Name:</label> <input id="lastName"
name="lastName" placeholder="Last Name" class="form-control"
type="text" value="" />
</div>
<div class="form-group">
<label for="email">Email:</label> <input id="email" name="email"
placeholder="Email" class="form-control" type="text" value="" />
</div>
<div class="form-group">
<label for="password">Password:</label> <input id="password"
name="password" placeholder="Password" class="form-control"
type="text" value="" />
</div>
<!-- /.modal-content -->
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save Customer</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// For demo to fit into DataTables site builder...
$('#invoicedtls').removeClass('display').addClass(
'table table-striped table-hover');
$('#invoicepayments').removeClass('display').addClass(
'table table-striped table-hover');
$('#existingcustomer').removeClass('display').addClass(
'table table-striped table-hover table-compact');
// Jquery draggable
$('.modal-dialog').draggable({
handle : ".modal-header"
});
</script>
What i am confusing is, when using a modal form, in controller class, i cannot separate the #RequestMapping value, because the value will always "/trproduct". In this controller class, i want to save 2 different table (SlInvoiceHdr and MsCustomer), but with the same #RequestMapping value.
I am using the same jsp for the add customer modal.
How can i do it in my controller ?
Thank You
Add the expected parameter to your request mapping
#RequestMapping( method = RequestMethod.GET , params = { "expectedparam" })
1 controller, 2 methods with the same requestMapping, but with different parameters
#RequestMapping(value = "/trproduct", method = RequestMethod.GET) public ModelAndView trproduct(Locale locale, HttpSession session) {
second:
#RequestMapping( method = RequestMethod.GET, params = { "newform" }) public String showAddCustomerForm(Model model, HttpSession session) {
But you have to add the the parameter "newform" to your url, like /trproduct?newform=true

ng-view expression is; not working

index.cshtml
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/App/App.js"></script>
<script src="~/App/Controllers/FlightCtrl.js"></script>
</head>
<body>
<div id="wrapper">
Hi
#*<resolve-loader></resolve-loader>*#
<div class="nav navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav" >
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li class="dropdown">
<a>Add Flight</a>
</li>
</ul>
</div>
</div>
</div>
<div ng-view> </div>
</body>
</html>
App.js
var AirReservationApp = angular.module("AirReservationApp", ['ngRoute']);
AirReservationApp.config(['$routeProvider',
function ($routeProvider)
{
$routeProvider.
when('/Admin', { templateUrl: 'App/Views/Flights/AddFlight.htm', controller: 'FlightCtrl' }).
otherwise({
redirectTo: '/Admin'
});
}
]);
AddFlight.html
<div ng-controller="FlightCtrl">
<ng-form name="formFlight">
<div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<label class="col-xs-12 col-sm-12 col-md-12 col-lg-12" for="question">Question <span class="mandatory">*</span> </label>
<div class="form-group col-xs-9 col-sm-9 col-md-8 col-lg-8"
<input type="text" name="FlightCode"
ng-required="=true" existnamevalidate valid="YN"
placeholder="Enter Flight Code"
ng-model="CreateFlight.Flight.FlightCode">
<span class="help-block"
Flight code is required.>
</span>
<span class="help-block"
This Flight Code already exists.>
</span>
</div>
</div>
<!--ng-show="isTextType"-->
<div class="row btn-pos-change">
<div class="col-md-12 padding-top-12 btn-blocks">
<div class="form-group">
<button type="button" class="btn btn-success pull-right"
>
{{saveBtnText}}
</button>
</div>
</div>
</div>
</div>
</ng-form>
</div>
FlightCtrl.js
var FlightCtrl = angular.module("FlightCtrlModule", []);
FlightCtrl.controller("FlightCtrl", ["$scope", "$rootScope", "$timeout", "$window", "$route",
function ($scope, $rootScope, $timeout, $window, $route)
{
alert('Hello');
$scope.saveBtnText = "Create";
}]);
The expression {{saveBtnText}} does not show 'Create'. Can any one help me on this.
Try this.
First create the FlightCtrlModule module on top of the AirReservationApp module in the App.js and the inject it to the AirReservationApp module.
App.js
angular.module("FlightCtrlModule", []);
var AirReservationApp = angular.module("AirReservationApp", ['ngRoute', 'FlightCtrlModule']);
AirReservationApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/Admin', { templateUrl: '/home.html', controller: 'FlightCtrl' }).
otherwise({
redirectTo: '/Admin'
});
}
]);
Now attach the FlightCtrl controller to the AirReservationApp module to have access to the FlightCtrlModule module.
FlightCtrl
//var FlightCtrl = angular.module("FlightCtrlModule", []);
AirReservationApp.controller("FlightCtrl", ["$scope", "$rootScope", "$timeout", "$window", "$route",
function ($scope, $rootScope, $timeout, $window, $route) {
alert('Hello');
$scope.saveBtnText = "Create";
}]);
UPDATE
If you want to keep your approach, what you can do is, move the flight controller above the app.js like so:
<script src="~/App/Controllers/FlightCtrl.js"></script>
<script src="~/App/App.js"></script>
And then inject the module FlightCtrlModule to the AirReservationApp module, like so:
var AirReservationApp = angular.module("AirReservationApp", ['ngRoute', 'FlightCtrlModule']);
both way have the same result.
Example Project - Dropbox

How to make tab to stay in the current tab after submitting the form?

I have 3 submit forms in tabs.after submitting the form it displays the message registration successfully. But it goes to home page so only after clicking the particular tab I can see the message. I want to make the tab to stay in the current tab after submitting the form.
<div class="tabs">
<form id="target">
<ul class="tab-links">
<li ><a href="#tab1" id="tabs-A" >Incident Report</a></li>
<li>Death Report</li>
<li><a href="#tab3" id="tabs-C" >Negative Case Data</a></li>
</ul>
<div class="tab-content">
<div id="tab1" class="tab ">
<p>
<?php
include("Report1.php");
?>
</p>
</div>
<div id="tab2" class="tab">
<p>
<?php
include("Report2.php");
?>
</p>
</div>
<div id="tab3" class="tab">
<p>
<?php
include("Report3.php");
?>
</p>
</div>
</div>
</form>
</div>
this is my jquery:
<script>
jQuery(document).ready(function() {
jQuery('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
// Show/Hide Tabs
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
// Change/remove current tab to active
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
</script>
this is my Report1.php.
<?php
include_once 'dataAccessControl.php';
$DataAccessController = new DataAccessController();
if (isset($_POST['report1']))
{
$daydropdown111=$_POST['daydropdown111'];
$monthdropdown111=$_POST['monthdropdown111'];
$yeardropdown111=$_POST['yeardropdown111'];
$dreport_place=$_POST['dreport_place'];
$dreport_address=$_POST['dreport_address'];
$dreport_additional=$_POST['dreport_additional'];
}
else
{
$daydropdown111="";
$monthdropdown111="";
$yeardropdown111="";
$dreport_place ="";
$dreport_address="";
$dreport_additional="";
}
if (isset($_POST['report1']))
{
$death = $DataAccessController->death_reports($_POST['daydropdown111'],$_POST['monthdropdown111'],$_POST['yeardropdown111'],$_POST['dreport_place'], $_POST['dreport_address'], $_POST['dreport_additional']);
if ($death) {
echo"<p><font color=red size='5pt' > Your Report has been Registered</font></p>";
//header("Refresh:3;url='deathReport.php'");
}
}
?>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Death Report</title>
<script type="text/javascript">
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield)
{
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=0; i<=31; i++)
dayfield.options[i-1]=new Option(i, i)
dayfield.options[today.getDate()-1]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=1999
for (var y=0; y<45; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
</head>
<body >
<div id="color" >
<table>
<h1 align="center"><p>Death Report</h1>
<form action="" method="POST">
<tr><td>Date </td><td>
<select name="daydropdown111" id="daydropdown111"></select>
<select name="monthdropdown111" id="monthdropdown111"></select>
<select name="yeardropdown111" id="yeardropdown111"></select>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
populatedropdown("daydropdown111", "monthdropdown111", "yeardropdown111")
</script>
</td></tr>
<tr><td></br> Place of </td><td></br><select name="dreport_place"id="wgtmsr">
<option value="hospital" >Hospital</option><option value="residence">Residence</option><option value="others">Others</option></select></td></tr>
<tr><td>Address </td><td></br><textarea name="dreport_address" rows="5" cols="32" id="loc" value=""> </textarea></td></tr>
<tr><td>Additional Cases if any</td><td></br> <textarea name="dreport_additional" rows="5" cols="32" id="loc" value=""> </textarea></td></tr></label></td></tr>
<tr><td></td><td><input type="submit" name="report1" value="Save" id="btnsize" /></td></tr>
</form>
</table></br>
</div>
</body>
</html>

When click on submit button it navigates to New page with same window **dynamically loading** using `meteor`

I am try to when click on Form submit button it navigates to new page with same window dynamically but it is not loading the details but it navigates to that page.I am sending my code also please help me.
Html page
<head>
<title>sample</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="container">
{{> header}}
{{> body}}
{{> footer}}
</div>
<div class="row-fluid">
{{render-Router}}
</div>
</body>
<template name="header">
<header>
<div class="header">
<img src="./logo.png" style="height:100px;width:200px;"/>
</div>
</header>
</template>
<template name="body">
<div class="bgbody">
<div align="center">
<form id="login-form" action="/admindetails">
<table>
<p class="admin">Admin Login</p>
<tr>
<td><p for="username">Admin Name</p></td>
<td><input type="text" id="username" name="username" placeholder="UserName"></td>
</tr>
<tr>
<td><p for="password">Password</p></td>
<td><input type="password" id="pwd" name="password" placeholder="password"></td>
</tr>
<td></td><td><input class="btn btn-success" type="submit" value="Log In"></td>
<td><input class="btn btn-capsule" type="button" value="New User"></td>
</table>
</form>
</div>
</div>
</template>
<template name="footer">
<div class="footer">
<div style="padding:20px;">
<div class="footerlinks"><p>AboutUs</p></div>
<div class="footerlinks">|</div>
<div class="footerlinks"><p>ContactUs</p></div>
<div class="copyright"><p>Copyright#Healt_Care</p></div>
</div>
</div>
</template>
Client code:
if (Meteor.isClient) {
Meteor.Router.add({
'/admindetails':'admindetails'
})
Template.body.events
({
'submit #login-form' : function (e,t)
{
/* template data, if any, is available in 'this'*/
if (typeof console !== 'undefined')
console.log("You pressed the button");
e.preventDefault();
/*retrieve the input field values*/
var email = t.find('#username').value
, password = t.find('#pwd').value;
console.log(email);
Meteor.loginWithPassword(email, password, function (err)
{
if (err)
{
console.log(err);
alert(err.reason);
Session.set("loginError", true);
}
else
{
console.log(" Login Success ");
Meteor.Router.to("/admindetails");
}
});
}
});
}
You manage the submit event yourself, so there's no need to set up the action parameter of the form. Setting that parameter causes browser to load target page on submit. Simply remove the parameter and things should work as intended.

Resources