Spring MVC Redirect to the Same JSP - spring

I am trying to write a Spring MVC application, in which if a certain value is present in the DB, the JSP should redirect to its own page and display some extra some information using JQuery. I have my controller written as:
#Controller
public class ConfigPushController {
#Autowired
#Resource(name = "deviceDetailsService")
DeviceDetailsService deviceDetailsService;
#RequestMapping(value = "/config", method = RequestMethod.GET)
public ModelAndView welcome(#RequestParam(name="name", required = false, defaultValue = "World") String userName, ModelMap modelMap) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
userName = authentication.getName();
ModelAndView modelAndView = new ModelAndView("configuration");
modelMap.put("name", userName);
if (!modelMap.containsAttribute("doesExist")) {
modelMap.addAttribute("doesExist", "init");
}
modelAndView.addAllObjects(modelMap);
return modelAndView;
}
#RequestMapping(value = "/verifyIP", method = RequestMethod.POST)
public ModelAndView verifyRouterIP(#RequestParam(required = true) String routerIP, ModelMap modelMap) {
boolean doesExist = deviceDetailsService.getDeviceDetailsByIPAddress(routerIP);
ModelAndView modelAndView = new ModelAndView("redirect:/config");
if (doesExist) {
modelMap.addAttribute("doesExist", "true");
} else {
modelMap.addAttribute("doesExist", "false");
}
modelAndView.addAllObjects(modelMap);
return modelAndView;
}
}
And my JSP, I have written like this:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<title>Router Console</title>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var doesExist = '${doesExist}';
if (doesExist == "init") {
$('#verify_success').hide();
$('#verify_fail').hide();
$('#command_header').hide();
$('#command_text').hide();
$('#command_area').hide();
} else if (doesExist == "true") {
$('#verify_success').show();
$('#command_header').show(20);
$('#command_text').show(30);
$('#command_area').show(40);
} else if (doesExist == "false") {
$('#verify_success').show('slow');
}
$(document).on('submit', 'formSubmit', function(e) {
var ip = $('#ip_text').val();
var header = $("${_csrf.parameterName}").attr("content");
var token = $("hidden[name='_csrf']").attr("content");
$.ajax({
type: "POST",
url: "/verifyIP",
data: $('#ip_text').val(),
beforeSend: function(request) {
request.setRequestHeader(header, token);
},
dataType: "text/plain",
contentType: "text/plain",
success: function(html) {
$('#verify_fail').show('slow');
$('#command_header').show(20);
$('#command_text').show(30);
$('#command_area').show(40);
}
});
e.preventDefault();
});
});
</script>
<form id="formSubmit" action="/verifyIP" method="POST">
<div id="heading" align="left" style="font-family: Verdana; color: blue; font-size: 20px">Welcome ${name} to CISCO Console</div>
<div id="mainSection">
.
.
.
.
.
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</div>
</form>
</body>
</html>
The problem I am having, is every time I redirect to the JSP, the attribute doesExist shows up as init, so the else blocks do not execute. Even if I set the value to true or false. Did i write the controller logic correctly?

Related

How can i send a list of an object to my controller?

I try to send a list of object to controller but controller always receives it as null.
var model= #Html.Raw(Json.Encode(Model.MultipleElements));
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: '#Url.Action("AddField", "Flux")',
data: model,
success: function (response) {
$(".destinationMultiple").html(response);
}
});
And here is my controller action
public PartialViewResult AddField(List<Destination> model)
{
return PartialView("_myPartialView");
}
You can use Ajax.Beginform. If you want you can do the following, which explains how to pass arrays from View to Controller.
View/Controller
namespace Testy20161006.Controllers
{
public class Destination
{
public string aDestination { get; set; }
}
public class TahtohViewModel
{
public List<Destination> MultipleElements { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public PartialViewResult AddField(List<Destination> MultipleElements)
{
List<String> sendout = new List<string>();
foreach (Destination dest in MultipleElements)
{
sendout.Add(dest.aDestination);
}
ViewBag.SendoutList = sendout;
return PartialView("_myPartialView");
}
public ActionResult Tut149()
{
Destination dest1 = new Destination { aDestination = "adest1" };
Destination dest2 = new Destination { aDestination = "adest2" };
Destination dest3 = new Destination { aDestination = "adest3" };
TahtohViewModel tahtoViewModel = new TahtohViewModel { MultipleElements = new List<Destination>() };
tahtoViewModel.MultipleElements.Add(dest1);
tahtoViewModel.MultipleElements.Add(dest2);
tahtoViewModel.MultipleElements.Add(dest3);
return View(tahtoViewModel);
}
View
#model Testy20161006.Controllers.TahtohViewModel
#using Testy20161006.Controllers
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut149</title>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
var items = [];
var q = $("input[name='theElemsName']");
$.each(q, function (index, thevalue) {
var item = {};
item.aDestination = thevalue.value;
items.push(item);
});
jQuery.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("AddField", "Home")',
data: JSON.stringify(items),
success: function (response) {
//alert("success");
$(".destinationMultiple").html(response);
}
});
})
})
</script>
</head>
<body>
<div>
<table>
#{ var index = 0;}
#foreach (Destination item in Model.MultipleElements)
{
<tr><td>Item <span>#(index++)</span></td><td data-multipleelements="#(index)">#Html.TextBox(item.aDestination, null, new { Name = "theElemsName", Value = item.aDestination })</td></tr>
}
</table>
<input type="button" id="theButton" value="Add Field" />
<div class="destinationMultiple"></div>
</div>
</body>
</html>
Partial View
my partial view
#foreach (string item in ViewBag.SendoutList)
{
<div>#item</div>
}

View not updating when model changed

I have a single page UI, which looks like below .
on the UI there are two checkboxes, when user toggle the states of checkbox, I use ajax to post the status to HomeController in a POST action.
after updated the model in POST action with the new checkboxes states, I redirect back to GET action to return a view.
however, the UI does not refresh with the new model.
can someone help on this ? thanks.
Views/Home/Index.cshtml
#{
Layout = "_Layout";
}
#model WebApplication5.Controllers.HomeModel;
<h1>STS</h1>
<div>
<input type="checkbox" id="UseVersionCheckBox" />Use version v1 in url
</div>
<br />
<div>
<input type="checkbox" id="ResponseTypeTokenCheckBox" /> Return access token in url
</div>
<div>your check status : #Model.IsChecked</div>
<br />
<div>your text : #Model.Text </div>
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - WebApplication5</title>
</head>
<body>
#RenderBody()
<script src="~/jquery-2.1.0.min.js"></script>
#RenderSection("Scripts", required: false)
<script type="text/javascript">
$(document).ready(function () {
function fun() {
var current = $("#UseVersionCheckBox").prop("checked");
var current2 = $("#ResponseTypeTokenCheckBox").prop("checked");
alert("values as:" + current + "," + current2);
var json = {};
json.UseVersionChecked = current;
json.ResponseTypeTokenChecked = current2;
var text = JSON.stringify(json);
$.ajax({
type: "POST",
url: "Home/Index",
data: text,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (r, s, e) {
},
success: function (r) {
},
complete: function () {
}
});
}
$("#UseVersionCheckBox").click(fun);
$("#ResponseTypeTokenCheckBox").click(fun);
});
</script>
</body>
</html>
HomeController.cs
public class HomeController : Controller
{
public HomeController()
{
}
public IActionResult Index()
{
HomeModel model;
if (TempData.ContainsKey("model"))
{
var newmodel = JsonConvert.DeserializeObject<HomeModel>(TempData["model"].ToString());
model = newmodel;
}
else
{
model = new HomeModel();
model.IsChecked = false;
model.Text = "not checked";
}
ModelState.Clear();
return View(model);
}
[HttpPost]
public IActionResult Index([FromBody] CheckStatus status)
{
HomeModel model = new HomeModel();
model.IsChecked = true;
model.Text = "UseVersionCheckBox : " + status.UseVersionChecked + " ; ResponseTypeTokenCheckbox : " + status.ResponseTypeTokenChecked;
if (TempData.ContainsKey("model"))
TempData.Remove("model");
TempData.Add("model", JsonConvert.SerializeObject(model));
ModelState.Clear();
return RedirectToAction("Index", "Home");
}
}
[Serializable]
public class HomeModel
{
public bool IsChecked { get; set; }
public string Text { get; set; }
}
public class CheckStatus
{
public bool UseVersionChecked { get; set; }
public bool ResponseTypeTokenChecked { get; set; }
}
weird thing , after checked the response of redirect to GET action, the new value is there ,but web page in browser still show old. why ?

AJAX, Thymeleaf Spring dynamic value change

I'm stuck in the response of ajax spring controller response.
My thymeleaf template code as under:
<div id="categoryContent" class="row no-margin">
<div id="catTitle" class="col-md-12 no-padding">
<h2 th:text="${ctaModule.getCtaSubTitle()}"></h2>
<p class="starting-msrp">Starting at: <span id="price" th:text="${category.getPrice()}"></span></p>
</div>
<h3 class="roof-wheelbase col-xs-12" th:utext="${ctaModule.getCtaDesc()}"></h3>
</div>
<div class="row no-margin category-model-price">
Ajax call:
function get_vehicle_categories()
{
var catController = $('#catTitle h2').html().toLowerCase().replace(/\s+/g, '');
var heightInner = $('#height-inner').find('.active').find('.carousel-caption').html();
var lengthInner = $('#length-inner').find('.active').find('.carousel-caption').html();
$.ajax({
url: './' + catController + '/{height}/{length}',
type: "GET",
dataType: "json",
contentType: 'application/json',
data: {
height: heightInner,
length: lengthInner
},
success: function(response) {
console.log(response);
},
error: function(e) {
console.log(e.Message);
}
});
}
My controller:
#RequestMapping(value = SiteUrls.CATAGORY_PAGE + "/{height}/{length}", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String ajaxCategoryVan(#PathVariable("site") String site,
#RequestParam(required = false) String height, #RequestParam(required = false) String length,
Model model) {
AssemblerDTO data = new AssemblerDTO();
data.setSite(site);
if((height == null || height.equals("")) || (length == null || length.equals(""))) {
data.setBody("cargo");
data.setRoof("std");
data.setWheelbase("144");
data.setGvwr("8550");
data.setPowertrain("2500");
} else {
data.setBody("cargo");
if(height.equalsIgnoreCase("Standard Roof")) {
data.setRoof("std");
data.setGvwr("8550");
data.setPowertrain("2500");
} else if(height.equalsIgnoreCase("High Roof")) {
data.setRoof("high");
data.setGvwr("8550");
data.setPowertrain("2500");
} else if(height.equalsIgnoreCase("High Roof Extended")) {
data.setRoof("superhigh");
data.setGvwr("8550");
data.setPowertrain("2500");
}
if(length.equalsIgnoreCase("144 Wheelbase")) {
data.setWheelbase("144");
data.setGvwr("8550");
data.setPowertrain("2500");
} else if(length.equalsIgnoreCase("170 Wheelbase")) {
data.setWheelbase("170");
} else {
data.setWheelbase("170E");
}
}
setModel(data, model);
return "category";
}
I'm receiving parameters successfully.
I need to change the data as above thymeleaf template.
Kindly help me out.

MVC3 ajax return new view

I have some code which displays a dropbox with a list of entries from a database and calls a controller action on the change event. The controller takes the selected entry as a string and returns a new view (I think herein lies my issue), the trouble is I think that the old view still remains as the newly returned view is never displayed.
Do I need to redesign this or if not, should I be forcibly destroying any old view?
My code is as follows:
EditSchool view:
#model namespace.Models.SchoolDetails
#{
ViewBag.Title = "EditSchool";
Layout = "~/Views/AuthorisedAdmin/_LayoutAdmin.cshtml";
}
<script src="#Url.Content("~/Scripts/chosen/chosen.jquery.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/bubble-popup-chosen-upload-functions.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#School").change(function () {
var SelectedSchool = $('#School').val();
$.ajax({
url: '/AuthorisedAdmin/RetrieveSchool'
, type: 'POST'
, data: { School: SelectedSchool }
, success: function (data) {
}
, error: function (request, textStatus, errorThrown) {
alert(errorThrown.toString());
}
, complete: function (request, textStatus) {
}
});
});
});
</script>
<fieldset>
<legend>Select School</legend>
<div class="editor-field">
#Html.DropDownList("School", ViewBag.RegisteredSchools as SelectList, namespace.Models.Helpers.LanguageSchoolsConstants.m_sDropdownDisplayText,
new
{
id = "School",
#class = "chosen",
})
</div>
</fieldset>
#{
if (null != Model)
{
#Html.Partial("Partial/EditSchoolPartial", Model)
}
else
{
#Html.Partial("Partial/NoSchoolSelected")
}
}
Note that the partial view (EditSchoolPartial) is probably not a concern here, so I'm not posting the code.
Controller methods of interest:
EditSchool action:
public ActionResult EditSchool()
{
List<string>kRegisteredSchools = DBHelperFunctionsSchool.Instance().GetRegisteredSchoolsNamesOnly();
ViewBag.RegisteredSchools = new SelectList(kRegisteredSchools, "Name");
SchoolDetails schoolDetails = null;//DBHelperFunctionsSchool.Instance().GetSchoolDetailsForName(kRegisteredSchools.FirstOrDefault());
return View(schoolDetails);
}
RetrieveSchool action (called by AJAX):
[HttpPost]
public ActionResult RetrieveSchool(string School)
{
SchoolDetails schoolDetails = null;
List<string> kRegisteredSchools = DBHelperFunctionsSchool.Instance().GetRegisteredSchoolsNamesOnly();
ViewBag.RegisteredSchools = new SelectList(kRegisteredSchools, "Name");
try
{
schoolDetails = new SchoolDetails();
schoolDetails.School = DBHelperFunctionsSchool.Instance().GetSchoolForName(School);
DBHelperFunctionsSchool.Instance().PopulateSchoolDetailsSuppData(schoolDetails);
schoolDetails.ActionNameToExecuteOnFormSubmit = "EditSchoolDetails";
schoolDetails.ControllerNameToExecuteOnFormSubmit = "AuthorisedAdmin";
}
catch
{
schoolDetails = null;
}
finally
{
}
return View("EditSchool", schoolDetails);
}
Instead of doing ajax on onchange ,do below
$("#School").change(function () {
var SelectedSchool = $('#School').val();
window.location='/AuthorisedAdmin/RetrieveSchool?School='+SelectedSchool;
});
Note:You may have to give full path url instead of relative url.

How to Show The image from one view to other view in Asp.Net WebApi MVC4?

HI all i have some images which i am retrieving dynamically and displaying in a view like this
here is my controller
private ProductEntities products = new ProductEntities();
public List<ProductItems> GetAllProducts()
{
var items = new List<ProductItems>();
var records = products.Products.ToList();
foreach (var item in records)
{
ProductItems model = new ProductItems();
model.ProductID = item.ProductId;
model.ProductName = item.ProductName;
model.ImageURL = item.ImageURL;
items.Add(model);
}
return items;
}
and this is my index page view
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/api/ProductDetails", function (data) {
$.each(data, function (idx, ele) {
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
$("#makeMeScrollable").append('<h4>' + ele.ProductName + '</h4>');
});
});
});
</script>
</head>
<body>
<h1>Products</h1>
<div class="rightsection_main">
<div class="img_main" id="makeMeScrollable">
</div>
</div>
</body>
now what i want is when ever an user clicks on a image i have to pass the ID of the image to my method in my apicontroller and i have to display that image in another view ..how do i pass my image to another view and Id to my api/controller action
i have to pass my ProductID to this method
public IEnumerable<ProductItems> ProductDeatils(long ProductID)
{
var productdeatils = products.ExecuteStoreQuery<ProductItems>("GetProductDetail #ProductID ", new SqlParameter("#ProductID", ProductID));
return productdeatils ;
}
The thing is that API actions do not return views. They are used to serialize models using some format such as JSON or XML. So when you are saying that you want to use the ProductDeatils API action to display a view, this doesn't make much sense. Views are returned by standard ASP.NET MVC controller actions returning ActionResults. So let's see how to set this up.
Let's suppose that you have the following API controllers:
public class ProductsController : ApiController
{
private ProductEntities products = new ProductEntities();
public IEnumerable<ProductItems> Get()
{
return products.Products.ToList().Select(item => new ProductItems
{
ProductID = item.ProductId,
ProductName = item.ProductName,
ImageURL = item.ImageURL
});
}
}
public class ProductDetailsController : ApiController
{
private ProductEntities products = new ProductEntities();
public ProductItems Get(long id)
{
return products.ExecuteStoreQuery<ProductItems>(
"GetProductDetail #ProductID ",
new SqlParameter("#ProductID", id)
);
}
}
Alright, now we will need standard ASP.NET MVC controller that will serve the views:
public class HomeController : Controller
{
public ActionResult Products()
{
return View();
}
public ActionResult ProductDetail(long id)
{
using (var client = new HttpClient())
{
var productDetailUrl = Url.RouteUrl(
"DefaultApi",
new { httproute = "", controller = "productdetails", id = id },
Request.Url.Scheme
);
var model = client
.GetAsync(productDetailUrl)
.Result
.Content
.ReadAsAsync<ProductItems>()
.Result;
return View(model);
}
}
}
and the respective view for showing the list of products and the detail of a product when a link is clicked:
~/Views/Home/Products.cshtml:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h1>Products</h1>
<div class="rightsection_main">
<div class="img_main" id="makeMeScrollable">
</div>
</div>
<script type="text/javascript" src="~/scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
var productsUrl = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "products" })';
var productDetailUrl = '#Url.Action("productdetail", "home", new { id = "__id__" })';
$.getJSON(productsUrl, function (data) {
$.each(data, function (idx, product) {
$('<img/>').attr({ src: product.ImageURL }).appendTo('#makeMeScrollable');
$('#makeMeScrollable').append(
$('<h4/>').html(
$('<a/>', {
href: productDetailUrl.replace('__id__', product.ProductID),
text: product.ProductName
})
)
);
});
});
</script>
</body>
</html>
and ~/Views/Home/ProductDetail.cshtml:
#model ProductItems
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ProductDetail</title>
</head>
<body>
<h4>#Html.DisplayFor(x => x.ProductName)</h4>
<img src="#Model.ImageURL">
</body>
</html>

Resources