Can a _Layout.cshtml have a controller - model-view-controller

I want to add navigation from database in _Layout.cshtml. I've created a controller for this and create _Layout.cshtml as a list view but its not working
This is my view code
#model IEnumerable<ITM_College.Models.field_tbl>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<nav>
<ul>
#foreach (var item in Model)
{
<li> #Html.DisplayFor(modelItem => item.Field_Name)</li>
}
</ul>
</nav>
Controller code
public class SharedController : Controller
{
ITMCollegeEntities db = new ITMCollegeEntities();
// GET: Shared
[ChildActionOnly]
public ActionResult _Layout()
{
var li = db.field_tbl.ToList();
return View(li);
}
}

No, but there are various ways to solve it:
1) Create base controller class or another tooling class that contains some common utilities that should be shared between your controllers.
2) PartialView and Html.RenderAction
[ChildActionOnly]
public ActionResult Something(string p)
{
var entities = repository.GetEntities(p);
var partialViewModel = new PartialViewModel(entities);
return PartialView(partialViewModel);
}

Related

Whyt Jquery ajax post does'nt work with HtmlUnit

i am using htmlunit with spring test in order to test all ihm interface from my web application. It works fine with html form (post and get) and with ajax get but i have a problem with ajax post request.
The controller don't received the request. If i replace post by get the junit test case works fine.
this the html view
<html lang="fr" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Html Unit</title>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
function postTest() {
$.ajax({
type:"post",
data: {
'subject' : 'subject test',
'message' : 'message test'
},
url:"[[#{/test/post}]]",
success: function(data, textStatus, jqXHR){
$("#result").text(data);
}
});
}
</script>
</head>
<body>
<h4 th:text="'Hello to Thymeleaf '+${myParam}">Hello from Thymeleaf</h4>
<button type="button" onClick="postTest()">Test post</button>
<div>
<span>result :</span><span id="result"></span>
</div>
</body>
and the controller
#Controller
public class WelcomeController {
#GetMapping("/")
public String init(Model model) {
model.addAttribute("myParam", "Guillaume");
return "welcome";
}
#PostMapping("/test/post")
public #ResponseBody String post(#RequestParam String subject, #RequestParam String message, Model model) {
return subject + " " + message;
}
}
you can also find the complete code on my github https://github.com/guisimon28/spring-test-htmlunit
Can you help me to find if there is some missing configuration or if its a htmlunig bug or pull request ?
Thanks for All
Guillaume

String is null on Thymeleaf page after adding to model

My controller:
#Controller
public class IndexController {
#RequestMapping(value = "/index")
public String index(Model model) {
model.addAttribute("message", "Hello World!");
return "index";
}
}
My page:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset = "ISO-8859-1" />
<link href = "css/styles.css" rel = "stylesheet"/>
<title>Spring Boot Application</title>
</head>
<body>
<h4>Spring boot.</h4>
<p th:utext="${message}"></p>
</body>
</html>
Upon loading and rendering, this HTML appears; how do I get the message to appear?
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1" />
<link href = "css/styles.css" rel = "stylesheet"/>
<title>Spring Boot Application</title>
</head>
<body>
<h4>Spring boot.</h4>
<p></p>
</body>
</html>
Ensure you have imported the thymeleaf dependency into your project.
Use th:text="${message}"
Method in IndexController is never being called, because this:
#RequestMapping(value = "/index")
Should be this:
#RequestMapping(value = "/")

Flash attributes and ResourceBundleViewResolver

I am facing an issue with the flash attributes which I have not able to retrieve it in the GET phase of POST/redirect/GET scenario. This is only happening when I use the ResourceBundleViewResolver.
view resolver
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="spring-views" /> </bean>
view properties
form.(class)=org.springframework.web.servlet.view.JstlView
form.url=/WEB-INF/pages/form.jsp
home.(class)=org.springframework.web.servlet.view.JstlView
home.url=/WEB-INF/pages/home.jsp
home_redirect.(class)=org.springframework.web.servlet.view.RedirectView
home_redirect.url=home
form.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="register" method="post">
Name: <input type="text" name="name"/> <br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h2> ${status} </h2>
</body>
</html>
so in this page, home.jsp, the status should contain the value set as the flash attribute.
controller
#Controller
public class WebController {
#RequestMapping(value="/form", method=RequestMethod.GET)
public String showFormPage(){
return "form";
}
#RequestMapping(value="/register", method=RequestMethod.POST)
public ModelAndView login(#RequestParam("name") String name, RedirectAttributes flashMap){
System.out.println("name = " + name);
flashMap.addFlashAttribute("status", "Registered successfully");
//return new RedirectView("home"); -- with this returned its working
return new ModelAndView("home_redirect"); //-- with this returned its not working
//return "redirect:home"; // -- not working
}
#RequestMapping(value="/home")
public String showHomePage(){
return "home";
}
}
on the whole this is the observation made:
if used resource bundle view resolver
return view names as string - not working
return ModelAndView - not working
return RedirectAndView - working
if used internal view resolver
return view names as string - working
2 return modelandview - cannot be used to redirect
return RedirectAndView - working

What is layout/template/themes in codeigniter

I'm new in codeigniter, I feel trouble about layout/template/themes in codeigniter.
I don't know when should using one of them..
What is the best way that i can do? if i want to make a website with free a html/css template like
goodnatured
|--img
|--img01.jpg
|--css
|--style.css
|--js
|--jquery.js
|--index.html
Anyone can tell me a tutorial, suggest, ... thanks
I just write little additional library(application/libraries/display_lib.php) for rendering tempates and similar page blocks.
Something like this:
class Display_Lib{
private $_CI;
private $_template_data;
public function __construct()
{
$this->_CI =& get_instance();
}
public function set($key, $value)
{
$this->_template_data[$key] = $value;
}
public function get($key)
{
return $this->_template_data[$key];
}
public function get_template_data()
{
return $this->_template_data;
}
public function display_page($view, $data = array())
{
$this->set('content', $this->_CI->load->view($view, $data, TRUE));
$this->_CI->load->view('templates/main_template', $this->get_template_data());
}
}
Set this library in auto load:
$autoload['libraries'] = array('session', 'database', 'display_lib');
And call it in controller:
class Main extends CI_Controller{
public function index()
{
$some_data = array();
$this->display_lib->display_page('views/main_view', $some_data);
}
}
Template example:
<!DOCTYPE html>
<html lang="en">
<head>
<base href="<?=base_url();?>">
<meta charset="utf-8">
<link rel="icon" href="<?=site_url('img/favicon.ico')?>" type="image/x-icon"/>
<link rel="stylesheet" href="<?=site_url('css/style.css');?>" type="text/css" media="screen, projection"/>
<script type="text/javascript" src="<?=site_url('js/jquery-1.10.2.min.js');?>"></script>
<title>Some page title</title>
</head>
<body>
<header></header>
<div class="auth_wrapper">
<div class="content">
<?=$content;?>
</div>
<div class="buffer"></div>
</div>
<footer></footer>
</body>
</html>
And application/views/main_view simple exmaple:
<div>Come content will be here</div>
This lib allow to use templates and render views from controllers.
Templates handle the layout of your page. You create a template that will contain your meta, header, footer, and a space for the body. The body get injected in the template, this is where the content change.
The idea is that most of the site don't change, only the body changes. This is where templates are useful, they save you time and increase consistency.
See this template library, it's pretty good: http://getsparks.org/packages/template/show
Themes is combined with a template as templates often define the layout and a theme just 'skin' the layout. A theme include assets and styles that will modify the template further more.
Cheers
Make a template.php, header.php, footer.php. Below is template.php, Similarly make header and footer and place them all in views folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" href="<?=site_url('img/favicon.ico')?>" type="image/x-icon"/>
<link rel="stylesheet" href="<?=site_url('css/style.css');?>" type="text/css" media="screen, projection"/>
<script type="text/javascript" src="<?=site_url('js/jquery-1.10.2.min.js');?>"></script>
<title>Some page title</title>
</head>
<body>
<header><?=$this->load->view('header');?></header>
<div class="wrapper">
<div class="content">
<?=$main?>
</div>
</div>
<footer><?=$this->load->view('footer');?></footer>
</body>
</html>
In your Controller function:
function index(){
$data = array();
$data['main'] = "home"; #this view is home.php in views folder, the content part of template.php
$this->load->view('template', $data); #this is the template file being rendered.
}
This is the most simple way of using templates in CI I think.

Stream MP3 file MVC3

I am trying to stream a file using the audio HTML5 tag. I have put the Controller action to return a FileStream and attached it to the src for the audio. However, the content is not loading into the audio tag and doesn't play when I press the default play button. I know the controller is working when I access the src directly. However, it doesn't work in the HTML5 audio tag.
Can anyone tell me what I am missing?
You should not return a FileStream, you should return a FileStreamResult or a FilePathResult from your controller action, like this:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult MyAudio()
{
var file = Server.MapPath("~/app_data/test.mp3");
return File(file, "audio/mp3");
}
}
and the ~/Views/Home/Index.cshtml view:
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sound Sample</title>
</head>
<body>
<article class="audio">
<header>
<h2>Some audio</h2>
</header>
<audio controls>
<source src="#Url.Action("myaudio")" type="audio/mp3" />
<p>Your browser does not support HTML 5 audio element</p>
</audio>
</article>
</body>
</html>

Resources