Variables contain values but in action they equals NULL - javascript

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.

Related

How can print object list using thymeleaf in 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";
}

datatable.select in cshtml with javascript parameter

my model code
public class viewCase
{
public List<string> lstCategory { get; set; }
public DataTable dtWrkTsk { get; set; }
}
my controller code
string query = "SELECT WorkFlowID,Subject,Category FROM CMSTasksWorkFlow"
objcase.dtWrkTsk = objdataclas.ExecuteDataTable(query);
return View("../ViewCases/CasesScreen",objcase);
my cshtml code
function getCaption() {
var cat= $("#layout option:selected").text(); //variable for select condition
var arr = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(
Model.dtWrkTsk.Select("Catagory='" + cat + "'") )); //<- error here
}
its giving me error 'cat ' does not exist in current context
and if i try
function getCaption() {
var cat= $("#layout option:selected").text(); //variable for select condition
var arr = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(
Model.dtWrkTsk.Select("Catagory='" +#<text> cat </text> + "'") ));} //<- error here
CS1660: Cannot convert lambda expression to type 'string' because it
is not a delegate type
<div id="addTask" class="modal fade " aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content round">
<div class="modal-header"><h4>New Task </h4></div>
<div id="tbody" class="modal-body" style="height:20%">
#Html.DropDownList("layout", Model.lstCategory.Select(m => new SelectListItem { Text = m, Value = m }), "All", new { onclick = "getCaption()" })
<div id="dtask" style="width: 80%; overflow: scroll; ">
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-primary" >OK</button>
<button type="button" data-dismiss="modal" class="btn">Cancel</button>
</div>
</div>
</div>
</div>
i am trying to keep datatable disconnected from server so whenever user changes value in Html.DropDownList function getCaption() is called
i only need select condition in datatable where i select category with javascript varible passing
how do i pass my javascript variable in datatable.select
The #Html.Raw() in var arr = #Html.Raw(...) is razor code which is parsed on the server before its sent to the view. It includes a .Select() query that uses a javascript variable which does not exist at that point - its not in scope.
You need to assign the collection to a javascript variable, and the filter the resulting array in javascript based on the selected option.
The following assumes dtWrkTsk is a collection of a model containing a property string Category, and you want to filer the collection to return only objects whose Category value matches the selected option
#Html.DropDownList("layout", Model.lstCategory.Select(m => new SelectListItem { Text = m, Value = m }), "All")
or
#Html.DropDownList("layout", new SelectList(Model.lstCategory), "All")
<script>
// Assign the collection to a javascript array
var arr = #Html.Raw(Json.Encode(Model.dtWrkTsk))
$('#layout').change(function() {
var selectedCategory = $(this).val();
// Return all objects in the collection that match
var result = $(arr).filter(function(index, item) {
return item.Category === selectedCategory;
});
.... // do something with the results
});
</script>
Additional suggest reading - Unobtrusive JavaScript

Cannot get correct syntax for #Html.ListBoxFor()

I've a series of #Html components which are built dynamically including ListBoxFor(). With the others I've given them an ID which I then use to populate a model value called inputvalues, which holds the values of each component whenever it changes. This works well but I had to change the original DropDownListFor() for ListBoxFor() but although the new syntax works, I cannot assign it an ID value as I did before without getting a syntax error. The code looks like this..
#if (Model != null)
{
#Styles.Render(BundleConfig.Styles_MultiSelect)
IEnumerable<SelectListItem> filetypes = from filetype in Model.ListOptions
select new SelectListItem
{
Value = filetype.ID.ToString(),
Text = filetype.Name,
Selected = Model.SelectedListOptionID == null ? false : Model.SelectedListOptionID > 0
};
<div class="editor-section">
<div class="label">
#Html.DisplayEditLabel(Model.Label, Model.Required.Value)
</div>
<div class="field large-text-field">
#*Original drop down replaced by ListBoxFor() but with ID
#Html.DropDownListFor(m => m.SelectedListOptionID, new SelectList(Model.ListOptions, "ID", "Name", Model.SelectedListOptionID).OrderBy(l => l.Value), new Dictionary<string, object>{
{"id", "personField_" + Model.ID}})*#
#Html.ListBoxFor(m => m.ListOptions, filetypes, new { #class = "multiselectFileTypes" })
</div>
</div>
}
#Scripts.Render(BundleConfig.Scripts_MultiSelect)
<script>
$("#personField_" + "#Model.ID").change(function () {
cnt++;
var uploadValue = JSON.stringify({
"id": "#Model.ID",
"order": cnt,
"required": "#Model.Required",
"libraryUploadConfigType": 3,
"customFieldTypeID": 5,
"selectedListOptionID": $(this).val()
});
inputValues = inputValues + uploadValue;
});
$(".multiselectFileTypes").multiselect({
noneSelectedText: 'All Options',
minWidth: 230,
selectedList: 6
});
</script>
Although the syntax for the original DropDownlistFor() worked and updated inputvalues the component didn't work. Having changed it to ListBoxFor() the component works but I can't seem to assign the ID 'personField_' without getting an error.
Any help would be appreciated.
I can't see that you try to assign ID in your ListBoxFor helper.
It should be like this:
#Html.ListBoxFor(m => m.SelectedListOptionIDs, filetypes, new { #class = "multiselectFileTypes" })
And SelectedListOptionIDs field of your model should be IList or IEnumerable, or Array of your ID type (probably IList<int>). Then it will work fine on View and bind correct on form POST.
See reply from Stephen Meucke above.

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.

How to use a javascript variable in url.action with ASP.NET MVC WebForms view engine

I want to redirect the user to a url in a javascript function.
editClick: function () {
var myid = 1;
location.href = '<%= Url.Action("ActionName", "ControllerName", new { id = myid})%>';
};
But 'myId' does not exist in the current context. How do I use a js variable in Url.Action?
An approach that I've taken in the past is to generate the link in the view like so:
<div class='clickmaster'>
<div class='clicker' id='#Url.Action("ActionName", "ControllerName", new { id = Model.Id })'>
Show Something Here
</div>
<div class='clicker' id='#Url.Action("ActionName", "ControllerName", new { id = Model.Id })'>
Show Something Here
</div>
</div>
Then in the javascript I defined a function like this:
$(function() {
$('.clickmaster').on('click', '.clicker' , function() { location.href = this.id; })
});

Categories