I'm trying to implement the select2 on my master layout of my ASP.NET MVC 4 website.
I want it to, as soon as the user starts typing (minimum of 2 letters), call my method to query the database using the letters the user has already typed. Except, when I start typing, my method never gets called. I threw in some alerts and I'm able to see what I'm typing, but the select2 isn't firing, I think.
Here's the script and css references in the tag:
<script src="/Content/select2/select2.js"></script>
<link href="/Content/select2/select2.css" rel="stylesheet" />
Here's the search box in my layout.cshtml file:
<div class="navbar-header hidden-xs pull-right" style="padding-top: 10px; margin-left: 10px;">
<input id="search" class="form-control" placeholder="Search..." type="text" data-autocomplete-url="/Home/AutoFillValues" />
</div>
And here's the bottom of my layout page where the select2 stuff appears:
<script src="/Scripts/jquery-1.9.1.min.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#RenderSection("scripts", required: false)
<script type="text/javascript">
$(document).ready(function () {
$("#search").select2({
placeholder: "Search...",
minimumInputLength: 2,
ajax: {
url: "~/Home/AutoFillSearch",
dataType: 'jsonp',
data: function(search) {
return {
q: search
};
},
results: function(search, page) {
return { results: data.Results };
}
}
});
});
</script>
Lastly, here's my controller method (I'm not worried about the code here yet, I just want to see my breakpoint get hit at the first line...):
public ActionResult AutoFillValues()
{
// Get all wrestlers and all teams
var players = _playerRepo.Query().Where(w => w.Division == "Division I" && w.Conference != null);
var schools = players.Select(w => w.School).Distinct();
ArrayList list = new ArrayList();
foreach (var school in schools)
{
var hyperlinkFormat = "{1}";
//#HttpUtility.UrlEncode(Model.Team.Name, System.Text.Encoding.UTF8)
list.Add(string.Format(hyperlinkFormat, string.Format(RosterPath, school), string.Format(RosterText, school)));
}
foreach (var player in playerss)
{
var hyperlinkFormat = "{1}";
//#HttpUtility.UrlEncode(Model.Team.Name, System.Text.Encoding.UTF8)
list.Add(string.Format(hyperlinkFormat, string.Format(RosterPath, player.School), string.Format(RosterText, player.School)));
}
return Json(list.ToArray());
}
I had to upgrade to jQuery 2.1 (because of the issue with version 1.9 and the .live/.on functions) in order for my select2 to start firing.
Now I just need to get my select2 styled...
Related
I need to change the view in same page using ajax when the user changes the option of the drop-down list.
Up until now in my view I have the drop down list
<div class="wrapper">
<div>
<label>Get cars per people </label>
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
</div>
<div class="box box-success">
<div class="box-body">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</div>
</div>
Then in a script (which I found from another question)
$(document).ready(function () {
$("#ddlChangeID").change(function () {
var strSelected = "";
$("#ddlChangeID:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "/Cars/Index/" + strSelected;
$.post(url, function (data) {
});
});
})
And in the controller I am using ViewBag values to save the drop-down list values and whatever else is needed for the graph which loads in a different script again with ViewBag values. I have managed to pass the selected value (strSelected) but the view does not reload with the new data.
How should I make the ajax event?
Change your script ajax call by calling an action result as follows
$("#ddlChangeID").change(function () {
$.ajax({
url: "/Controller/ActionHtml?id="+$('#ddlChange').val(),
type: "POST",
cache: false,
success: function (result) {
$("#myChart").html(result);
},
error: function () {
$("#myChart").empty();
}
});
});
and in the controller the actionresult will be like the following which returns the html partial view that you need to append
public ActionResult ActionHtml(string id)
{
//Here you can load the data based on the id,pass model to the patial views etc
ViewBag.id = id;
return PartialView("~/Views/Shared/myhtml.cshtml");
}
myhtml.cshtml will be a partial view with the html content as
//content is dummy,change the content as you want
<!DOCTYPE html>
<html>
<body>
<p>Enter some text in the fields below, then press the "Reset form" button to reset the form.</p>
<form id="myForm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
</form>
So I changed the
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
To
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #onchange = "ChangeOption()" })
adding also an id to the main div.
And the script to
function ChangeOption() {
var id = $('#ddlChange').val();
$.ajax({
url: '/Cars/Index',
type: "GET",
data: { Id: id },
success: function (data) {
$('#wrapAll').html(data);
}
});
}
It seems to work. Only issue now is that the css breaks.
It pushes the graph and drop-down list to the right breaking
the functionality.
I am trying to create a cascading DropDownList on ASP.NET RazorPage. After doing some research I found the most common way to do the task is utilizing jQuery in my View. Nearly all demos and examples I found online implement a cascading DropDownList in previous ASP.NET versions, more specifically MVC. I tried translating these examples in the context of how I need them but I am having no luck, most likely due to syntax errors and/or other reasons.
I am using ASP.NET Core 2.2
I am having trouble specifically implementing the dynamic function call (GetSubCategory) whenever an item is selected in the first DropDownList which is displaying correctly
<form asp-controller="my_dropdown" asp-action="CreatePortfolio" method="post" class="form-horizontal" role="form">
<div class="form-group">
<div class="row">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<label for="CategoryName">Category</label>
#Html.DropDownList("categorylist",
new SelectList((System.Collections.IEnumerable)ViewData["categorylist"], "CategoryId", "CategoryName"), "Select Category", "CategoryName")
<label for="SubCategoryName">Subcategory</label>
#section scripts{
<script type="text/javascript">
//Insert default item "Select" in dropdownlist on load
$(document).ready(function () {
var items = "<option value='0'>Select</option>";
$("#colorselect").html(items);
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#CategoryId").on("change", function () {
$list = $("#SubCategory");
$.ajax({
type: "GET",
url: '/CreatePortfolio',
data: { id: $("#CategoryId").val() },
traditional: true,
success: function (response) {
$list.empty();
$.each(result, function (i, item) {
$list.append('<option value="' + item["SubCategoryId"] + '"> ' + item["SubCategoryName"] + '</option>');
});
},
error: function () {
alert("Something went wrong"); // Hide loader icon
},
});
})
})
</script>
}
</div>
</div>
</div>
Code behind the view
public JsonResult GetSubCategory(int CategoryId)
{
subcategorylist = _context.GetAllSubCategories(CategoryId);
//ViewData["subcategorylist"] = subcategorylist;
return new JsonResult(subcategorylist);
}
public void OnGet()
{
// ----- Getting Data From Database Using Stored Procedure -----
categorylist = _context.GetAllCategoires();
// ----- Assigning categorylist to ViewData["categorylist"] in order to access it in the view -----
ViewData["categorylist"] = categorylist;
}
I want the code to correctly display the SubCategories associated to the Category by CategoryId which is a field in both classes/tables
I have a page which is being populated with a list of checkboxes for each record in the database. The user can select as many checkboxes as they want and the system should save their responses. I'm having a hard time getting my array of selected checkboxes to pass through to my Controller.
When i run my code and click the submit button i get a Maximum call stack size exceeded and i'm not sure how to solve that.
Image of the browser console error message: http://imgur.com/a/BnKLL
.cshtml:
#{
ViewBag.Title = "Subject";
}
<head>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<h2>Explore Subjects</h2>
<div>
<button id="SubmitButton">Save Changes</button>
<div style="border-bottom:solid">
<h4>Your Followed Subjects</h4>
<div id="FollowedSubjects">
#foreach (var subject in Model.FollowedSubjects)
{
<input type="checkbox" name="SubjectCheckBox" checked="checked" value=#subject.SubjectId>#subject.SubjectDetail.Subject<br>
}
</div>
</div>
<div id="AllSubjects">
<br />
<h4>More Subjects to Follow</h4>
<p>Ordered by number of bills with subject</p>
#foreach(var subject in Model.AllSubjects)
{
<div class="subjectDisp">
<input type="checkbox" name="SubjectCheckBox" value=#subject.Subject.SubjectId>#subject.Subject.Subject (#subject.Count) <br>
</div>
}
</div>
</div>
<script>
$(document).ready(function () {
$('#SubmitButton').click(function () {
var checkboxes = document.getElementsByName("SubjectCheckBox");
var checked = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checked.push(checkboxes[i]);
}
}
$.ajax({
url: '#Url.Action("FollowSubjects", "Home")',
type: 'POST',
data: { Parameters: checked },
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
alert("there")
});
});
</script>
My controller funtion that im trying to call.
[HttpPost]
public ActionResult FollowSubjects(int[] Parameters)
{
int i = 0;
return View();
}
Eventually i will have this hit the database but for now i just put a breakpoint at int i = 0; to see what gets passed to the function.
You can send it as an array of string and convert them to int at server side or Stringify it and send
var checked=""
$(checkboxes).each(function () {
checked += this + ',';
i++;
ajax --> data: { Parameters: checked },
[HttpPost]
public ActionResult FollowSubjects(string Parameters)
{
// Do your task
return View();
}
I have a mvc 5 project using a database.
In my project I have a Blog-page. This page is loaded using a controller.
In the page I dynamically create a list of items (blogitems) using a simple '#foreach(var item in collection).
Each item has an id (off course), a title and a description.
#foreach (var item in Model.VmBlogItems)
{
<div class="allblogs">
<div class="blogtitle">
<h4>#item.Title</h4>
</div>
<div id="allblogcontent">
#item.Description
</div>
<a id="moreless" href="">Lees meer</a>
</div>
}
My question now is how I can create a button so that when clicked on it the description is hidden or shown.
I also wrote some jquery:
<script type="text/javascript">
//when ready
$(function () {
$('#allblogcontent').hide();
$('#moreless').click(function () {
$('#allblogcontent').toggle();
});
});
</script>
However when I try this, all my items show or hide the Description.
Does anybody know how I make sure that only the Description of the selected item is shown or hidden? I just spend 6 hours reading, trying and sadly enough failing to make it work. I could use some help.
First you modify the markup so each description tag has a unique id attached to it, and the corresponding button has a reference to that id
#{
int i=0;
}
#foreach (var item in Model.VmBlogItems)
{
i++;
<div class="allblogs">
<div class="blogtitle">
<h4>#item.Title</h4>
</div>
<div id="allblogcontent#i" class='someclass'>
#item.Description
</div>
<a id="moreless" href="" data-desc-id='allblogcontent#i'>Lees meer</a>
</div>
}
Your code can figure out which is which now.
<script type="text/javascript">
//when ready
$(function () {
$('.someclass').hide();
$('#moreless').click(function () {
$('#' + $(this).attr('data-desc-id')).toggle();
});
});
</script>
A footnote
This approach will make static references between the tags, so you can move the markup around if you like. The other two solutions shown here, so far, will break if you change the order of the tags.
Just change the below section from
$('#moreless').click(function () {
$('#allblogcontent').toggle();
});
to
$('#moreless').click(function () {
$(this).siblings('#allblogcontent').toggle();
});
When I select Date in DateTimePicker, it's invoking public ActionResult Index(DateTime? test). It returns some items into the view, but those items do not appear on Index. It seems that this does not work, and I'm unsure why:
<h1>Items</h1>
#foreach (var item in Model)
{
<br />#item.Date
}
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<Table> temp = new List<Table>();
return View(temp);
}
[HttpPost]
public ActionResult Index(DateTime? test)
{
masterEntities m = new masterEntities();
List<Table> temp = m.Table.Where(key => key.Date == test).Select(key => key).ToList();
return View(temp);
}
}
Index.cshtml:
#model IEnumerable<DatePicker.Models.Table>
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$('#datetimepicker1').datetimepicker({ useCurrent: false });
$('#datetimepicker1').on("dp.hide", function (e) {
//var temp = $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm')
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
});
});
</script>
</div>
</div>
<h1>Items</h1>
#foreach (var item in Model)
{
<br />#item.Date
}
First you send an empty list to the view:
List<Table> temp = new List<Table>();
return View(temp);
So the loop doesn't show anything because, well, there's nothing to show. It's an empty list.
Then you make an AJAX request to get items:
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
});
But you don't do anything with those items. You basically ignore the response from the AJAX request.
So... The data doesn't display because you haven't written any code to display the data. The AJAX request should have some sort of callback function to do something with the returned response:
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
success: function (data) {
// do something with the response here
}
});
What you do with the response is up to you. Is it JSON? HTML? Based on the server-side code, it looks like it's HTML. So you can maybe put it into an element on the page. Something like this, perhaps:
$('#someElement').html(data);
That's just one example, and would of course require an element of some sort that you can identify to hold the response. You could do a lot of other things with the response.
One thing to note, however, is that your response appears to be an entire page. It includes script tags, link tags for CSS, and all sorts of markup that you otherwise already have on the client. So putting the entire page into an element isn't going to work right.
You might want to return just a partial view for this AJAX response. Or, otherwise, instead of using AJAX at all just navigate to the action to get that entire page.