Thymeleaf is trying to build a html which does not exist and which is not called anywhere - spring

I am trying to build a spring mvc app with spring boot and thymeleaf. I am trying to create a form to insert an object into my data base (something which I already do in my app and is working) but I constantly find this error:
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/views/error.html]")
(...)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/views/error.html]
(...)
This is the problem you usually find when you are trying to reference a template which does not exist or has a different name. Here's the thing. There is no Error.html in my views' folder as you can see in the print below:
Can anyone help me understand what's going on?
EDIT with more information:
Below you can find the endpoints which are giving me trouble:
#GetMapping("{id}/add-expense")
public String expensesForm(Model model, #PathVariable Long id){
model.addAttribute("expense", new Expenses());
model.addAttribute("budgetId", id);
return "expenseForm";
}
#PostMapping("{id}/add-expense")
public String expenseSubmitted(#ModelAttribute Expenses expense, #PathVariable Long id, Model model){
Budgets budget = budgetsRepository.getById(id);
if(budget != null){
budget.addExpense(expense);
expense.setBudget(budget);
expensesRepository.saveAndFlush(expense);
}
else{
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "not all variables there");
}
model.addAttribute("expense", expense);
return "expenseResult";
}
The GET endpoint seems to be working as intended. When I load the "id/add-expense" path it displays the page "expenseForm" correctly. The problem comes when I try to submit the form in the "expenseForm" template and go to the POST for "id/add-expenses". That is when I get a 400 bad request response. I am lead to believe that the problem might be that the "expenseForm" cannot correctly populate the #ModelAttribute in the POST method but I can't say why or how to fix it. In the console, I am given the error above which tells me that Thymeleaf cannot find the template for "error.html".
expenseForm.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Expense Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Expense Creation</h3>
</div>
<form action="#" th:action="#{/budgets/{id}/add-expense(id = ${budgetId})}" th:object="${expense}" method="post">
<p>Name: <input type="text" th:field="*{expenses_name}" /></p>
<p>Amount: <input type="number" th:field="*{expenses_amount}" /></p>
<p>Date: <input type="text" th:field="*{expenses_date}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</div>
</body>
</html>
expenseResult.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Expense Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Expense Created</h3>
</div>
<p th:text="'Name: ' + ${expense.expenses_name}" />
<p th:text="'Amount: ' + ${expense.expenses_amount}" />
<p th:text="'Date: ' + ${expense.expenses_date}" />
Submit another expense
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/budgetScript.js"></script>
</div>
</body>
</html>
Class Expenses:
#Entity(name = "expenses")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Expenses {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long expenses_id;
private String expenses_name;
private Integer expenses_amount;
private Date expenses_date;
#ManyToOne
#JoinTable(
name = "budget_expenses",
joinColumns = #JoinColumn(name = "expenses_id"),
inverseJoinColumns = #JoinColumn(name = "budgets_id"))
private Budgets budget;
//Gettes setters and constructor
}
Thank you in advance.
EDIT 2 after changing the name of "expenseResult.html" to "error.html":
So I decided to follow the tip from andrewJames and I changed the name of "expenseResult.html" to "error.html". I also changed the return value in the POST method from 'return "expenseResult"' to 'return "error"' and I am no longer given the 400 bad request error on the application. Instead, I am given the "error.html" page but the fields for expense.expenses_name, expense.expenses_amount or expense.expenses_date are not shown in the page. It is just an empty page with the "Expense Creation" text. In the console I receive a new error:
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "expense.expenses_name" (template: "error" - line 19, col 16)
(...)
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'expenses_name' cannot be found on null
(...)
From what we can see, the application cannot retrieve the fields from null, meaning that the #ModelAttribute Expenses expense is not returning the correct values from the form page. It more or less confirms my suspicion that the problem was in the modelAttribute but I continue to not know how to correct the problem since I have tried to verify multiple times if everything was okay and I found no issue. I also don't understand why it is looking for a "error.html" file considering that I had no prior mention to such a file in my code and project.
EDIT 3 after using ModelandView intead of ModelAttribute:
Following dsp_user's suggestion. I started by hardcoding the path with "/budgets/10/add-expense" instead of using {id} and the problem remained, which makes me believe that the problem is not the path.
I started using the ModelAndView, as can be shown below, but I continued to have the same problem as before (400 bad request).
#PostMapping("{id}/add-expense")
public ModelAndView expenseSubmitted(#ModelAttribute("expenses") Expenses expenses, #PathVariable Long id, Model model){
System.out.println("here");
Budgets budget = budgetsRepository.getById(id);
if(budget != null){
budget.addExpense(expenses);
expenses.setBudget(budget);
expensesRepository.saveAndFlush(expenses);
}
else{
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "not all variables there");
}
ModelAndView modelAndView = new ModelAndView("expenseResult");
modelAndView.addObject("expense", expenses);
return modelAndView;
}
EDIT 4 to add the Budgets logic:
Budgets:
#Entity(name = "budgets")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Budgets {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long budgets_id;
private String budgets_name;
private String budgets_description;
private Integer budgets_amount;
#OneToMany(mappedBy = "budget")
#JsonIgnore
private List<Expenses> expenses;
#Transient
public float budgets_expense_sum = 0;
//Gettes setters and constructor
}
Budget Creation Endpoints:
#GetMapping("new")
public String budgetsForm(Model model){
model.addAttribute("budget", new Budgets());
return "budgetForm";
}
#PostMapping("new")
public String budgetSubmitted(#ModelAttribute Budgets budget, Model model){
budgetsRepository.saveAndFlush(budget);
model.addAttribute("budget", budget);
return "budgetResult";
BudgetForm.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Budget Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Budget Creation</h3>
</div>
<form action="#" th:action="#{/budgets/new}" th:object="${budget}" method="post">
<p>Name: <input type="text" th:field="*{budgets_name}" /></p>
<p>Description: <input type="text" th:field="*{budgets_description}" /></p>
<p>Monthly Amount: <input type="number" th:field="*{budgets_amount}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</div>
</body>
</html>
BudgetResult.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Budget Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Budget Created</h3>
</div>
<p th:text="'Name: ' + ${budget.budgets_name}" />
<p th:text="'Description: ' + ${budget.budgets_description}" />
<p th:text="'Amount: ' + ${budget.budgets_amount}" />
Submit another message
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/budgetScript.js"></script>
</div>
</body>
</html>

Related

Spring-MVC Thymeleaf from not submitting

I'm new to spring and I've tried coding a prototype.
I've tried making a form. Whenever I press the submit-button, nothing happens.
I'm using Spring Boot 2.4.3 with Oracle OpenJDK 15.0.2. I've tried Firefox and Chrome. The js-console is empty.
This is my model (Patient.java):
public class Patient implements Serializable {
private long id;
private String firstname;
private String lastname;
// Geters and seters
}
My Controller (PatientController.java):
#Controller
public class PatientController {
#GetMapping("/patient")
public String patientForm(Model model) {
model.addAttribute("patient", new Patient());
return "addPatient";
}
#PostMapping("/patient")
public String patientSubmit(#ModelAttribute("patient") Patient patient, Model model) {
model.addAttribute("patient", patient);
return "addedPatient";
}
}
My addPatient.html:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTL-Testet Prototype</title>
</head>
<body>
<h1>Add a patient</h1>
<from action="#" th:action="#{/patient}" th:object="${patient}" method="post">
<p>Id: <input type="number" th:field="*{id}"/></p>
<p>Firstname: <input type="text" th:field="*{firstname}"/></p>
<p>Lastname : <input type="text" th:field="*{lastname}"/></p>
<button type="submit">Register</button>
</from>
</body>
</html>
My addedPatient.html:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTL-Testet Prototype</title>
</head>
<body>
<h1>Add a patient</h1>
<p th:text="'Added ' + '[' + ${patient.id} + ']' + ${patient.firstname} + ' ' + ${patient.lastname}"></p>
Add another patient
</body>
</html>
The from tag on the addPatient.hmtl page is wrong, if you change it to form tag as below, the problem is solved:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTL-Testet Prototype</title>
</head>
<body>
<h1>Add a patient</h1>
<form action="#" th:action="#{/patient}" th:object="${patient}" method="post">
<p>Id: <input type="number" th:field="*{id}"/></p>
<p>Firstname: <input type="text" th:field="*{firstname}"/></p>
<p>Lastname : <input type="text" th:field="*{lastname}"/></p>
<button type="submit">Register</button>
</form>
</body>
</html>

why wire:click not working in laravel livewire

laaravel version:8.0
livewire version: 2.x
Hi there
I am new to laravel livewire and facing a strange issue!. in order to execute the action i used wire:click as can be seen in the following code in my admin-login.blade.php
#section('content')
<div class="admin-login display-flex flex-align-items-center flex-justify-content-center">
<button wire:click="toDo">{{$login}}</button>
<div class="admin-form display-flex flex-direction-column flex-justify-content-center" >
#livewire('header',['name'=> 'Admin Login','width'=> '100%','height' => '20%'])
<form class=" display-flex flex-direction-column flex-justify-content-center" >
<section style="margin: 2%;">
<label for="Email">Email :<span style="color: red">*</span></label>
<input type="email" required>
</section>
<section style="margin: 2%;">
<label for="Password">Password :<span style="color: red">*</span></label>
<input type="password" required>
</section>
<button style="width: 40%; height: 5vh; align-self: center;justify-self: flex-end;">Login</button>
</form>
</div>
</div>
#endsection
my app.blade.php file in layouts directory is
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="{{asset('css/admin/app.css')}}">
#livewireStyles
<title>Admin Dashboard</title>
</head>
<body>
#livewire('nav-bar')
#livewire('side-bar')
#yield('content')
</body>
#livewireScripts
<script>
var isStudentDropDown = false
Livewire.on('showSidebar',()=>{
document.getElementById('sidebar').style.display = "block"
})
Livewire.on('closeSidebar',()=> {
document.getElementById('sidebar').style.display = "none"
})
Livewire.on('showDropdown',data => {
if(document.getElementById(data).style.display === "block"){
document.getElementById(data).style.display = "none"
}else{
document.getElementById(data).style.display = "block"
}
})
</script>
</html>
now my component php file
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class AdminLogin extends Component
{
public $login = "login";
public function render()
{
return view('livewire.admin-login');
}
public function hell(){
$this->login = "signup";
}
public function toDo(){
dd('do some thing');
}
}
i have checked my devtools and got no request being send to the server
Pardon me for any mistake!
Extends layouts from component
ref link https://laravel-livewire.com/docs/2.x/rendering-components#custom-layout
public function render()
{
return view('livewire.admin-login')
->extends('layouts.app')
->section('content');
}
and remove #section from admin-login.blade.php

Search page in spring mvc doesn't work

I Have created simple mvc CRUD. All works fine except search page.
Im getting errorr as follows:
HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
Controller page is:
#RequestMapping(value="/search")
public ModelAndView search(){
return new ModelAndView("search","command", new Emp());
}
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public ModelAndView search1(#ModelAttribute("name") Emp emp){
String name = null;
name = dao.searchname(name);
return new ModelAndView("searchemp","name",name);
}
Search.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>z
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
label {
text-align: right;
clear: both;
float:left;
margin-right:15px;
}
.box{background-color: #e1e8f0;}
body{background:#f0eceb;}
</style>
</head>
<body>
<div style=" left: 30%; top: 25%; position: absolute;">
<div class="col-sm-12 col-sm-offset-3 box " >
<center> <h1>Add New Employee</h1> </center>
<form method="post" action="jsp/searchemp/" >
<div class="form-group"> <div class="col-xs-7">
<label ><h5>Name :</h5></label>
<input name="name" class="form-control" placeholder="Enter Name of the employee" />
<button type="submit" value="Save" class="btn btn-primary btn-lg">Search</button>
</div></div>
</form>
</div>
</div>
</body>
</head>
Searchemp.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Employees List</h1>
<table class="table table-hover" border="1" width="70%" cellpadding="2">
<thead>
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th></tr></thead>
<tbody><tr>
<td>${String.id}</td>
<td>${String.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td>Edit</td>
<td>Delete</td>
</tr> </tbody>
</table>
<br/>
Add New Employee
jdbctemplate query:
public String searchname(String name) {
String query = "select * from Emp99 where name=?";
Object[] inputs = new Object[] {name};
String empName = template.queryForObject(query, inputs, String.class);
return empName;
}
Dont know what goes wrong.
help me.
in order for jsp to consume an bean , your controller method should return data,in your jsp you are trying to utilize
{String.id} and {emp.id} which is never passed from the controller method search1.so you need to add your beans to a model and
return the page like this.
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public String search1(#ModelAttribute("name") Emp emp,Model model){
model.addAttribute("emp",emp); //passing the model name and the bean ,
//model.addAttribute("name",anotherBean); //you can add many attributes as you wish.
return "searchemp";
}
now inside the searchemp.jsp you can utilize the emp bean like this.
{emp.id}
remove the {String.id} part. inside the searchemp.jsp which will not work.

I'm trying to change button text by calling action method using ajax.actionlink. That method is returning a string as button ID in new page

LAYOUT:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/bootstrap")
#Scripts.Render("~/bundles/modernizr")
<link rel="Stylesheet" href="../../Content/bootstrap.min.css" />
<link rel="Stylesheet" href="../../Content/bootstrap-theme.min.css" />
</head>
#*<body style="background-image: url(../../Content/Images/old-paper.jpg)">*#
<body style="background-color: #EEE">
#*---- WEB PAGE ---- *#
<div class="wrap-middle">
#*---- TITLE OF THE WEBSITE ----*#
<div class="container-fluid" style="width: 100%; background-image: url('/Content/Images/Header.bmp')">
<div>
<h1>
ONLINE VOTING SYSTEM</h1>
</div>
</div>
#*---- BODY SECTION ----*#
<div class="jumbotron">
<div class="container">
#RenderBody()
</div>
</div>
<div class="navbar navbar-inverse navbar-fixed-bottom" style="box-shadow: 0 0 20px black;">
<div class="container-fluid" style="color: Yellow">
Copyright <sup><span class="glyphicon glyphicon-copyright-mark"></span></sup>2014.
</div>
</div>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
VIEW:
#model IEnumerable<Online_Voting_System_site.DAL.tbl_candidate>
#{
ViewBag.Title = "CandidateApproval";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Ajax.ActionLink("Approve",
"ApproveCandidate",
new { _CandidateID = item.CandidateID },
new AjaxOptions { UpdateTargetId = item.CandidateID.ToString() },
new { #id = item.CandidateID.ToString(), #class = "btn btn-sm btn-success" })
ACTION METHOD:
public string ApproveVoter(string ID)
{
/* Logic is hidden.I use that ID parameter in here */
return "Approved";
}
I'm trying to change button text by calling action method using
ajax.actionlink. That action method is returning a string as button ID
but it displayed in new page.
Edit: The string should the text of the button. But the text is getting displayed in a new page.

Default values in ko.observable property not showing

I am trying out knockoutjs at the moment, with my fairly rudimentary knowledge of javascript. I have set up a basic ASP.NET MVC 3 app for this purpose. Here's the snippet I set up in the Home/Index.cshtml view:
#if(false)
{
<script src="../../Scripts/jquery-1.6.3.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-1.3.0beta.debug.js" type="text/javascript"></script>
}
#{
ViewBag.Title = "Home Page";
}
<script type="text/javascript">
var entryDataViewModel = {
registration: ko.observable("Registration"),
registeredName: ko.observable("Name"),
entryClass: ko.observable("Junior")
};
ko.applyBindings(entryDataViewModel);
</script>
<h2>#ViewBag.Message</h2>
<p>
Registration: <span data-bind="text: registration"></span><br />
Name: <span data-bind="text: registeredName"></span><br />
Class: <span data-bind="text: entryClass"></span><br />
To learn more about ASP.NET MVC visit http://asp.net/mvc.
</p>
For some weird reason nothing is showing, not even the default values. If I debug through Firebug the ViewModel is showing the properties as being empty too. Have I missed something here?
Many thanks,
Dany.
ADDED: the content of the _Layout.cshtml - it's all stock standard stuff, except for the addition of knockout, and using jquery 1.6.3
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/knockout-1.3.0beta.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.6.3.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
</head>
<body>
<div class="page">
<header>
<div id="title">
<h1>My MVC Application</h1>
</div>
<div id="logindisplay">
#Html.Partial("_LogOnPartial")
</div>
<nav>
<ul id="menu">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
</ul>
</nav>
</header>
<section id="main">
#RenderBody()
</section>
<footer>
</footer>
</div>
</body>
</html>
The answer I voted above only worked when I tried it in a plain webpage - not when I tried it in my MVC view. As it turned out I put the script block in the wrong position. I moved it to the end of the view, after the page elements have been processed. The other option is to wrap it within $(document).ready() then you can put the script block containing ViewModel and call to ko.applyBindings() anywhere you want...
use $(document).load(function(){:
<script type='text/javascript'>
//<![CDATA[
$(document).load(function(){
var entryDataViewModel = {
registration: ko.observable("Registration"),
registeredName: ko.observable("Name"),
entryClass: ko.observable("Junior")
};
ko.applyBindings(entryDataViewModel);
});
//]]>
</script>
Have a look: http://jsfiddle.net/S8Rh5/ - it works just fine.

Resources