How can print object list using thymeleaf in javascript? - javascript

I want receive object list using thymeleaf in javascript.
I am studying spring boot Please help me.
error message like below.
Multiple annotations found at this line:
- ',' expected.
<script>
/*<![CDATA[*/
let team=[[${teamMemberList.userid}]];
alert(team);
/*]]>*/
</script>
controller
#GetMapping(value = "/detail.do")
public String openPostDetail(#ModelAttribute("params") PostDTO params, #RequestParam(value = "pnum", required = false) Long pnum, Model model) {
PostDTO postDTO = postService.getPostDetail(pnum);
if (postDTO == null || "Y".equals(postDTO.getDeleteyn())) {
return "redirect:/main.do";
}
List<CommentDTO> commentList= commentService.getCommentList(pnum);
List<UserDTO> teamMemberList = teamMemberService.getTeamMembertList(pnum);
model.addAttribute("postDTO", postDTO);
model.addAttribute("commentList", commentList);
model.addAttribute("comment", new CommentDTO());
model.addAttribute("teamMemberList", teamMemberList); //this
model.addAttribute("teamMember", new UserDTO());
int countMember = teamMemberService.selectTeamMemberTotalCount(pnum);
model.addAttribute("countMember", countMember+1);
if (countMember >= postDTO.getMinpeople()){
model.addAttribute("minpeople", true);
System.out.println(countMember);
}
return "/detail";
}

Related

error JavaScript critical error ...: Expected ')'

I am getting error below while using ajax in asp.net MVC, and I have no idea what's wrong with it!
JavaScript critical error at line 161, column 101 in
http://localhost:50474/Home/Products\n\nSCRIPT1006: Expected ')'
Here is my View:
<p class="text-center"><a class="btn btn-primary" onclick="CreateOrder(#pr.ProId)" role="button">خرید</a>
Here my Action in controller:
[HttpPost]
public ActionResult CreateOrder(Guid productId)
{
Order or = new Order();
or.Number = 1;
or.ProductId = productId;
or.SessinId = Request.UserHostAddress;
int proprice = db.Products.Where(c => c.ProId == productId).Select(c => c.Price).FirstOrDefault();
or.TotalPrice = proprice * 1;
db.Orders.Add(or);
db.SaveChanges();
int count = (db.Orders.Where(c => c.SessinId == or.SessinId).Select(c =>
c.OrderId)).Count();
Session["ShopcartCount"]= count;
db.Dispose();
return RedirectToAction("Products", "Home");
}
And here is ajax code:
<script>
function CreateOrder(productId) {
$.ajax({
url: "/Home/CreateOrder/" + productId,
type: "post"
}).done(function (result) {
$("#shopcart").html(result);
});
}
$(function () {
$("#shopcart").load("/Home/ShopCartCount");
});
</script>
Please check this way you got this error
Here working example first button your code and second button working fine.
Click here
View
<p class="text-center"><a class="btn btn-primary" onclick="CreateOrder('#pr.ProId')" role="button">خرید</a>
Like #jishan siddique posted in his answer, you need to use single quotes ' ' around your model property '#pr.ProId' like CreateOrder('#pr.ProId)' instead of CreateOrder(#pr.ProId) for the Razor view to recognise it.

ASP.Net Razor Pages - How do you return json from a razor page to javascript $.getJson?

I am very new to web development and I've been searching around for a while now and I can't seem to find a solution to this. I am using razor pages in asp.net core 2.0 and I want to fill a drop down box based on another drop down box's selection. I set up the below javascript to hit a procedure in my razor page when the value of the first drop down box changes. When I run the code though, I can't get it to work. I think it is due to my return value but I can't seem to get that to be a json value as it keeps throwing an error at me when I try to. The error is that "JSON is not valid in this context". Can anyone suggest to me how to return JSON from razor pages to a javascript call?
Any help would be appreciated!
#section Scripts {
<script type="text/javascript">
$('#Department').change(function () {
var selectedDepartment = $("#Department").val();
var cardSelect = $('#Card');
cardSelect.empty();
if (selectedDepartment != null && selectedDepartment != '') {
$.getJSON('#Url.Action("GetCardsByDivisionAndStatus")', { divisionID: selectedDepartment }, function (cards) {
if (cards != null && !jQuery.isEmptyObject(cards)) {
cardSelect.append($('<option/>', {
Card_ID: null,
Card_Number: ""
}))
$.each(cards, function (index, card) {
cardSelect.append($('<option/>', {
Card_ID: card.Card_ID,
Card_Number: card.Card_Number
}));
});
};
});
}
});
</script>
}
And here is my C# code (I tried used JsonResult but that's not working either):
// If the user selects a division then make sure to get the cards for that division only
[HttpGet]
public ActionResult GetCardsByDivisionAndStatus(string divisionID)
{
int checkinStatus;
int intdivisionID;
if (divisionID != "0" && divisionID != null)
{
// Retrieve a status of checked in so that only cards with a checked in status can
// be checked out.
checkinStatus = linqQuery.GetCardStatusByStatusDesc("Checked In", _Context);
intdivisionID = Convert.ToInt32(divisionID);
// Retrieve list of cards that have the checkin status ID
CardList = linqQuery.GetCardListByStatusIDandDeptID(checkinStatus, intdivisionID, _Context);
// Create the drop down list to be used on the screen.
carddropdown = new List<CardDropDown>();
carddropdown = loaddropdowns.ReturnDropDownList(CardList);
return new JsonResult(CardList);
}
return null;
}
EDIT----------------------------------------------------------------------
So I changed the code as below and now I'm getting a parse error "JSON.parse: unexpected character at line 1 column 1 of the JSON data" I can't figure out what is going on as I can't see what the data is coming back that it can't parse. Is my code below not converting to JSON and if not, what am I missing?
#section Scripts {
<script type="text/javascript">
$('#Department').change(function () {
var selectedDepartment = $("#Department").val();
var cardSelect = $('#Card');
cardSelect.empty();
if (selectedDepartment != null && selectedDepartment != '') {
$.getJSON('#Url.Action("/CheckOutCard?handler=CardsByDivisionAndStatus")', { divisionID: selectedDepartment }, function (cards) {
if (cards != null && !jQuery.isEmptyObject(cards)) {
cardSelect.append($('<option/>', {
Card_ID: null,
Card_Number: ""
}))
$.each(cards, function (index, card) {
cardSelect.append($('<option/>', {
Card_ID: card.Card_ID,
Card_Number: card.Card_Number
}));
});
};
});
}
});
</script>
And here is my C# code for the procedure that I updated:
// If the user selects a division then make sure to get the cards for that division only
[HttpGet]
public JsonResult OnGetCardsByDivisionAndStatus(string divisionID)
{
int checkinStatus;
int intdivisionID;
if (divisionID != "0" && divisionID != null)
{
// Retrieve a status of checked in so that only cards with a checked in status can
// be checked out.
checkinStatus = linqQuery.GetCardStatusByStatusDesc("Checked In", _Context);
intdivisionID = Convert.ToInt32(divisionID);
// Retrieve list of cards that have the checkin status ID
CardList = linqQuery.GetCardListByStatusIDandDeptID(checkinStatus, intdivisionID, _Context);
// Create the drop down list to be used on the screen.
carddropdown = new List<CardDropDown>();
carddropdown = loaddropdowns.ReturnDropDownList(CardList);
var converted = JsonConvert.SerializeObject(carddropdown);
return new JsonResult(converted);
}
return null;
}
Rename your method to OnGetCardsByDivisionAndStatus (note "OnGet" prefix) and in jquery code change the url to
$.getJSON('/{PageRoute}?handler=CardsByDivisionAndStatus'
e.g.
$.getJSON('/About?handler=CardsByDivisionAndStatus'
Notice the handler querystring parameter name will be your method name without OnGet prefix.
So I figured out what the problem was. Apparently I did not need to have the #URL.Action in my code. It was causing me to not hit my C# code which in return caused a null response back to my call. I have modified my javascript code to be as below to show what I am talking about. Thanks Mohsin for trying to help me out.
#section Scripts {
<script type="text/javascript">
$('#Department').change(function ()
{
var selectedDepartment = $("#Department").val();
var cardSelect = $('#Card');
cardSelect.empty();
if (selectedDepartment != null && selectedDepartment != '')
{
$.getJSON("/CheckOutCard?handler=CardsByDivisionAndStatus", { divisionID: selectedDepartment }, function (cards)
{
$.each(cards, function (index, card)
{
cardSelect.append($('<option/>',
{
value: card.card_ID,
text: card.card_Number
}));
});
});
}
});
</script> }

Populate DropDownList from another DropDownList

I have two related models.
public partial class bs_delivery_type
{
public decimal delivery_id { get; set; }
public decimal delivery_city_id { get; set; }
public string delivery_address { get; set; }
public virtual bs_cities bs_cities { get; set; }
}
and the second one:
public partial class bs_cities
{
public bs_cities()
{
this.bs_delivery_type = new HashSet<bs_delivery_type>();
}
public decimal cities_id { get; set; }
public string cities_name { get; set; }
public virtual ICollection<bs_delivery_type> bs_delivery_type { get; set; }
}
and I have such ViewBag's for dropdownlist's:
ViewBag.city = new SelectList(_db.bs_cities, "cities_id", "cities_id");
ViewBag.delivery_adress = new SelectList(_db.bs_cities, "delivery_id", "delivery_address");
When I choose city in first dropdownlist, in the second one there has to be appeared binded list with delivery_adress, where delivery_city_id = cities_id(from first dropdownlist).
How to do that?
Edit:
I tryed method from #Izzy's comment, so here is my actual view:
#model Bike_Store.Models.DeliveryModel
#{
ViewBag.Title = "Checkout";
}
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
function GetDelivery(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddldelivery").html(procemessage).show();
var url = "/Shop/GetDeliveryByCityId/";
$.ajax({
url: url,
data: { cities_id: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select adress</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddldelivery").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h2>Checkout</h2>
#using (Html.BeginForm())
{
#Html.DropDownListFor(m=>m.CitiesModel, new SelectList(Model.CitiesModel, "cities_id", "cities_name"), new {#id = "ddldelivery", #style="width:200px", #onchange="javascript:GetDelivery(this.value);"})
<br />
<br />
<select id="ddldelivery" name="ddldelivery" style="width:200px">
</select>
<br /><br />
}
My controller now looks like this:
public List<bs_cities> GetAllCities()
{
List<bs_cities> cities = new List<bs_cities>();
foreach (var city in _db.bs_cities)
{
cities.Add(city);
}
return cities;
}
public List<bs_delivery_type> GetAllDeliveries()
{
List<bs_delivery_type> deliveries = new List<bs_delivery_type>();
foreach (var delivery in _db.bs_delivery_type)
{
deliveries.Add(delivery);
}
return deliveries;
}
[HttpPost]
public ActionResult GetDeliveryByCityId(decimal cities_id)
{
List<bs_delivery_type> delivery = new List<bs_delivery_type>();
delivery = GetAllDeliveries().Where(m => m.delivery_city_id == cities_id).ToList();
SelectList objDelivery = new SelectList(delivery, "delivery_id", "delivery_address", 0);
return Json(objDelivery);
}
public ViewResult Checkout()
{
DeliveryModel deliveryModel = new DeliveryModel();
deliveryModel.CitiesModel = new List<bs_cities>();
deliveryModel.CitiesModel = GetAllCities();
return View(deliveryModel);
}
The problem now is that i have 2 ddls, but works only first one.
In scrshot you can see I have a list of cities, when I choose a city, in this same ddl appears a list of delivery adresses, and when I choose adress - its desappears. What a magic? Help me please with Ajax.
List of cities
I guesse i fixed it, the problem was in:
#Html.DropDownListFor(m=>m.CitiesModel, new SelectList(Model.CitiesModel, "cities_id", "cities_name"), new {#id = "ddldelivery", #style="width:200px", #onchange="javascript:GetDelivery(this.value);"})
I changes #id = "ddldelivery" to #id = "ddlcity" and it works now
The following guide will show you:
Create a partial view
Takes cityid as input and outputs the delivery address list
Load partial view into your select
Note: Partial view solution may be overkill in this situation, but for similar problems it is actually quite usefull.
PartialView .cshtml
Filename: _deliveryTypePartial.cshtml
#model List<bs_delivery_type>
#foreach(var item in Model)
{
<option value="#item.delivery_id">
#item.delivery_address
</option>
}
Controller Code for Partial View:
public IActionResult _deliveryTypePartial(decimal city_id)
{
List<bs_delivery_type> model = context.bs_delivery_types.Where(row => row.delivery_city_id == delivery_city_id).ToList();
return PartialView(model);
}
And then Finally, for your AJAX
I notice that your two dropdownlists have identical ID's witch will cloud your javascript code and is considered bad practice, so for the purposes of this guide I will call the first dropdownlist:
ddlcity
Now, inside your onchange function for ddlcity:
$('#ddldelivery').load("/ControllerName/_deliveryTypePartial?city_id=" _stateId);
This should load the partial view into your second dropdown list.
PS: As I completed this question you had already used the direct ajax method, I agree that both methods are equally suitable in this case. You can perhaps use the method outlined here if the actual objects you need to populate are a lot more complex.

Kendo MVC Treeview get all checked nodes and pass them to the Controller

First time with MVC5 and Telerik... I am reading Active Directory and getting all the security groups to display in a TreeView. After an Admin is done selecting the Roles he/she shall press the Save Groups button and then the javascript is supposed to get all nodes and pass them to the controller. The controller will save to the database. I need to know how to access the datacontext for a given node. After I get the data context I can proceed to get all of the nodes context and pass it to the controller.
Kendo Treeview and Buttons:
#{
ViewBag.Title = "Configure";
}
#model IEnumerable<CMDB.Web.Models.AdminGroups>
<div>
<input id="save" type="button" value="Save Groups" onclick="SaveData()" />
<input id="return" type="button" value="Return" onclick="location.href='#Url.Action("Index", "Admin")'" />
#(Html.Kendo().TreeView()
.Name("treeview")
.Checkboxes(checkboxes => checkboxes
.Name("checkedFiles")
.CheckChildren(true)
)
.Events(events => events.Check("onCheck"))
.DataTextField("Name")
.AutoScroll(true)
.DataSource(source => source
.Model(model => model.Id("id").HasChildren("hasChildren"))
.Read(read => read.Action("GetActiveDircetoryGroups", "Configure"))
)
)
</div>
Javascript:
<script type="text/javascript" >
//show checked node IDs on datasource change
function onCheck() {
var treeView = $("#treeview").data("kendoTreeView");
var id = treeView.dataItem(e.node);
}
function SaveData() {
var AllSelectedNodes = new Array();
AllSelectedNodes = ($("#treeview .k-item input[type=checkbox]:checked").closest(".k-item"));
alert(AllSelectedNodes.join('\n'));
var myApiUrl = '#Url.HttpRouteUrl("DefaultAPI", new { controller = "AdminValues", action = "SaveSelectedAdmins"})';
var movies = $.ajax({
url: myApiUrl,
type: 'POST',
data: AllSelectedNodes
});
}
</script>
Controller:
[HttpPost]
public void SaveSelectedAdmins(IEnumerable<CMDB.Web.Models.AdminGroups> ag)
{
string Sids = string.Empty;
foreach (var s in ag)
{
var pc = new PrincipalContext(ContextType.Domain, "", "");//blank for security purposes
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Guid, s.id.Value.ToString());
if (s.id.Value.ToString() == gp.Guid.Value.ToString())
{
Sids = Sids + "," + gp.Sid;
}
}
using (var ctx = new Data.DBContext())
{
var d2 = (from d in ctx.Set<Entities.Config>()
where d.Property == "str"
select d).SingleOrDefault();
d2.Value = Sids;
ctx.SaveChanges();
}
}
Using $.post instead of $.ajax fixed the issue.

Variables contain values but in action they equals NULL

I have the following js code:
$("#dateRange").change(function() {
var date = $(this).attr("value");
var test = "1";
var eventId = $("div.movie").attr("eventid");
$("#scheduleList").load("/EventSchedule/GetSchedule/?date=" + date + "&dayRange=" + test + "&eventId=" + eventId);
});
This is action:
public EmptyResult GetSchedule(string date, string dayRange, string eventId)
{
// some code
}
In the firebug all variable filled correctly: date contain date, test contain 1 and eventId contain 12. But, in controller action dayRange and evendId equals null. The date param is filled.
Where is problem?
UPDATE:
div.movie:
<div class="movie" eventid="12" type="Film">
<div class="poster">
<img src="/Image/GetImage">
<div class="btn_buy_ticket">
<div>
<i></i>
<span>
Купить билет
</span>
<em></em>
</div>
</div>
</div>
</div>
My routes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var entryRoute = new PageEntry("page/{name}/",
new RouteValueDictionary(
new
{
controller = "DynamicPage",
action = "Index",
name = string.Empty
}),
new RouteValueDictionary(new { name = #".+" }),
new MvcRouteHandler());
routes.Add("display-page",
entryRoute);
routes.MapRoute(
"Activate",
"Account/Activate/{username}/{key}",
new
{
controller = "Account",
action = "Activate",
username = UrlParameter.Optional,
key = UrlParameter.Optional
});
}
Thanks.
Might be some parameter contain white spaces.
Check that cause I have faced same problem day before yesterday..
for dayRange you may want to use $("#selectdayRange").text()
you may also need to encodeURIComponent($("#selectdayRange").text()); in order to be able to insert a query parameter.
Try removing the /
$("#scheduleList").load("/EventSchedule/GetSchedule?date=" + date ...
If you've never fiddled with your Global.asax file, by default, URLs route to {controller}/{action}/{id}.
I would recommend using a ViewModel to pass your data, however, since you are using MVC.

Categories