I get typeahead working in my project but only for names. I am not able to process id of that particular label coming in autocomplete.
Bootstrap typeahead-
<input type="text" name="names" value="" id="typeahead" data-provide="typeahead" />
Script-
<script type="text/javascript">
$(function () {
$('#typeahead').typeahead({
source: function (term, process) {
var url = '#Url.Content("~/Invoice/GetNames")';
return $.getJSON(url, { term: term }, function (data) {
return process(data);
});
}
});
})
</script>
Json method-
[HttpGet]
public JsonResult GetNames(string term)
{
var names = (from u in db.Contacts
where u.name.Contains(term)
select u).ToArray();
var results = names.Select(u => u.name);
return new JsonResult()
{
Data = results,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
I am selecting whole table row on match. But How do I get Id with label name.
Or-
I can select whole row at server's side, But the problem persist for filtering result for label and name.
I used this info to also get the ID: http://fusiongrokker.com/post/heavily-customizing-a-bootstrap-typeahead (More complex... part)
Related
I have added a code to fetch values from a database to show multiple checkboxes as shown below on my view page
#{
var dept_list = ViewBag.department_list;
}
#foreach (var dept_item in dept_list)
{
<input type="checkbox" id="dept_checkbox" name="#dept_item.name" value="#dept_item.department_ID" />
<span class="rmargin20">#dept_item.name</span>
}
Now I want to get the values of the checked checkboxes, and want to save these values to the database. The above mentioned code will generate the checkboxes for each record in database.
This can be done in asp.net. But i want to implement this feature in MVC.
Hi You can use FormCollection for getting the form values..
see my below sample code :
public ActionResult MethodName(FormCollection form)
{
string CheckboxValue = form.Get("CheckBoxName_1"); //Dynamic checkbox name
return View();
}
Hope it helps you :)
if your view is strongly binds then just submit the form and get the checked value using above solution.
And if it is not then using jquery to save checked values.
use a class for each check box
<input type="checkbox" id="dept_checkbox" class="checkbox_dept" name="#dept_item.name" value="#dept_item.department_ID" />
<span class="rmargin20">#dept_item.name</span>
Now get checked values
var selectedDepts == null;
$('.checkbox_dept::checked').each(function (e) {
selectedDepts += this.value + "^";
});
//ajax call
$.post("../ControlerName/Save", { "strSelectedDepts": selectedDepts },
function (data) {
//saved successfully
}.fail(function (xhr, textStatus, errorThrown) {
//Error occured
});
in your controller file.
[HttpPost]
public string Save(string strSelectedDepts)
{
//remove last ^ char
string strData = strSelectedDepts.Substring(0, strSelectedDepts.Length - 1);
string[] arrData = strData.Split('^');
foreach(var itm in arrData)
{
//do save operation
}
}
Questions about ASP.NET MVC, Knockout.js and the mapping plugin abound. I have the following (very simple "getting started") example, which works. However, I would like feedback on whether this is the recommended approach. Primarily, I am interested in future models being significantly more complex (children, dropdowns, etc.). I feel maintaining two sets of models is not justifiable, thus my desire to use the mapping plugin.
PS: I wouldn't mind having the form submit, but I couldn't get that to work due to all different issues, apparently related to URL-encoding of string values with quotes by ko.utils.postJSON. Any updates on that would be appreciated also.
HTML
<h2>Simple View</h2>
<p>A simple model with 2 properties</p>
<p>Model property "Name": <span data-bind="text: Name"></span></p>
<p>Model property "Count" (just some integer): <span data-bind="text: Count"></span></p>
<form data-bind="submit: save">
<h3>Editing</h3>
<p>Name: <input type="text" data-bind="value: Name" /></p>
<p>Count: <input type="text" data-bind="value: Count" /></p>
<h3>Posting Back</h3>
<button type="submit">Update</button>
</form>
JavaScript
<script type="text/javascript">
var KoViewModel;
$(function () {
KoViewModel = ko.mapping.fromJSON('#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))');
ko.applyBindings(KoViewModel);
});
var save = function () {
$.ajax({
url: location.href,
type: 'POST',
data: ko.mapping.toJSON(KoViewModel),
contentType: 'application/json; charset=utf-8',
success: function (data) {
ko.mapping.fromJSON(data, KoViewModel);
}
});
}
</script>
Server-Side
public ActionResult Index()
{
Models.SimpleModel m = new Models.SimpleModel();
m.Name = "Some name";
m.Count = 1;
return View(m);
}
[HttpPost]
public JsonResult Index(Models.SimpleModel fc)
{
fc.Name += " (updated)";
fc.Count++;
return (new JsonResult() { Data = Newtonsoft.Json.JsonConvert.SerializeObject(fc) });
}
Thanks for any insights!
I would structure the script differently.
function SimpleModel(data) {
var self = this;
// data
self.Name = ko.observable();
self.Count = ko.observable();
// api
self.load = function (data) {
if (data) ko.mapping.fromJSON(data, {}, self);
};
self.save = function () {
return $.ajax({
type: 'POST',
url: location.href,
data: ko.mapping.toJSON(self),
contentType: 'application/json; charset=utf-8',
}).done(self.load);
};
// init
self.load(data);
}
// later... -------------------------------------------------------------------------
$(function () {
var data = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))';
ko.applyBindings( new SimpleModel(data) );
});
Advantages:
All data properties of the viewmodel are explicitly defined. This helps reduce bugs because it is immediately obvious what a viewmodel looks like. It also helps reduce run-time errors because properties will exist even if they happen to be missing on the JSON input. This way, the view can always bind without any problems.
You can move the viewmodel to a separate script file.
The viewmodel can initialize itself from the data you pass into the constructor. This will be useful if you refactor the application - for example when your viewmodel suddenly becomes a part of a larger viewmodel.
No awkward references to global variables or separate helper functions, the viewmodel is self-contained.
Returning the Ajax promise from the save method allows you to attach extra behavior without rewiring the viewmodel:
var vm = new SimpleModel(data);
// programmatically save the model
vm.save().done(function () {
// whatever
localStorage.setItem('lastAutoSave', Date.now());
});
I've created a jQuery Accordion using Asp.Net MVC, and it's working fine. The accordion displays a list of employee names, and when I click on an item, it shows the details. I'd like to send an AJAX request to get the employee details when they click on an item, instead of loading all the employee details at once. Please look at my code below.
Also, please tell me how to keep the first item in the accordion collapsed instead of showing the details, and is there any way to move the heading a bit to the right without using  ?
<div id="accordion">
#foreach (var item in Model.Employees)
{
<h3> #item.EmployeeName</h3>
<div id = "accordiondiv">
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
</div>
}
</div>
<script>
$(function () {
$("Accordion").click(function (evt) {
$.ajax({
url: "/Accordion/GetEmployeeDetails",
type: 'POST',
data:
//need code to pass the employeeid that was clicked on the accordion,
success: function (data) {
$.each(data, function (i, val) {
//need code to populate the respective accordion with the employee details
});
}
});
}
});
</script>
Here's a sample to send an AJAX request to the controller:
<div id="accordion">
#foreach (var item in Model.Employees)
{
<h3> #item.EmployeeName</h3>
<div id = "accordiondiv" data-id="#item.EmployeeId">
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
<p><input type="button" id="Accordion" class="btn" name="Accordion" /></p>
</div>
}
</div>
<script>
$(function () {
$(".btn").each(function (){
var button = $(this);
var parentDiv = button.parent();
var employeeId = parentDiv.attr("data-id");
button.click(function (){
$.ajax({
url: "/Accordion/GetEmployeeDetails",
type: 'POST',
data: { employeeId : employeeId},
success: function (data) {
$.each(data, function (i, val) {
//need code to populate the respective accordion with the employee details
});
}
});
});
});
</script>
And in your controller:
[HttpGet]
public ActionResult GetEmployeeDetails(int employeeId)
{
// code: get the details based on employeeId
var detail = new Model.EmployeeDetail();
return Json(detail, JsonRequestBehavior.AllowGet);
}
Thiago's implementation seems like it should work. However, I would create a partial view _EmployeeDetails with how you want the details to look, based on the Employee model,
#model Employee
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
In your controller you'll return it as such,
public ActionResult GetEmployeeDetails(int employeeId)
{
...
var employee = Repository.GetEmployee(employeeId);
return PartialView("_EmployeeDetails", employee);
}
Which result you can use to the set the content of each <div id="accordionDiv"> on the AJAX response,
<script>
$(function () {
$(".btn").each(function (){
var button = $(this);
var parentDiv = button.parent();
var employeeId = parentDiv.attr("data-id");
button.click(function (){
$.ajax({
url: #Url.Action("GetEmployeeDetails"),
type: 'POST',
data: { employeeId : employeeId },
success: function (data) { parentDiv.html(data); }
});
});
});
</script>
I have simple report page- a couple of text boxes where when data is entered and submitted I want to load the jqgrid on the same page asynchronously.
I am using the MVC version of JQGrid.
without a jqgrid I am able to load a table data and my view looks like below
#using (Ajax.BeginForm("GetReport", new AjaxOptions {UpdateTargetId = "result", HttpMethod = "Post" }))
{
<div class="editor-label">Start Date</div>
<div class="editor-field">#Html.Editor("StartDate", "DateTime")</div>
<div class="editor-label">End Date</div>
<div class="editor-field">#Html.Editor("EndDate", "DateTime")</div>
<input type="submit" value="Submit" />
}
<div id="result"></div>
instead of a result being a table I want to display a jqGrid in its place. A jqGrid which is defined as below.
#Html.Trirand().JQGrid(Model.ReportGrid, "ReportGrid")
How do I achieve this?
I'll step out how I would do it, which I think would work for you as well (I build a number of jqGrids with a MVC3 backend.
You already have the HTML component, or you could use something like this.
<div id="ExampleGridContainer" >
<table id="ExampleGridName" class="scroll" cellpadding="0" cellspacing="0" ></table>
<div id="ExampleGridPager" class="scroll" style="text-align:center;"></div>
</div>
Then for your Javascript you would need to include a reference to both (in this example I"m using English as my location)
<script src="#Url.Content("~/Scripts/trirand/i18n/grid.locale-en.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/trirand/jquery.jqGrid.min.js")" type="text/javascript"></script>
You could include this on your page if it was a one of or in your _Layout.chtml
Then inside your script portion on the view you could build somthing similar to
<script type="text/javascript">
$(document).ready(function () {
//initalize jqGrid
$('#ExampleGridName').jqGrid({
datatype: 'json',
url: '/ControllerName/ActionName',
colNames: [ 'ColumnOneName', 'ColumnTwoName']
colModel: [
{ name: 'ColumnOneName', //etc}
{ name: 'ColumnTwoName', //etc}
],
pager: $('#ExampleGridPager'),
rowNum: 5,
rowList: [5,10,20],
sortname: 'ColumnOneName',
//etc
//rest of grid settings
});
});
</script>
Now in the example above with the datatype: 'json', and the url: property filled out when the view is displayed and the ready event is processed your grid will go out to the URL and look for data. If you want to do this later on after another action, or repeat it dynamically you can start off with the datatype: 'local', and no url: property.
When it comes time to set these properties and reload the grid you would either:
//set the `datatype:` and `url:` properties and load the grid
$('#ExampleGridName').jqGrid('setGridParam', { datatype: 'json', url: '/ControllerName/ActionName' }).trigger('reloadGrid', [{ page: 1}]);
//reload the grid if the `datatype:` and `url:` properties are already configured
$('#ExampleGridName').jqGrid().trigger('reloadGrid', [{ page: 1}]);
On your Controller you would have an action that would be able to respond to the requests for data and produce the results in a JSON format. This by no means is anything beyond a basic example of how to get up and running with a MVC3 jqGrid with dynamic loading, and there are many more advanced filtering, searching, etc options.
public ActionResult ActionName(string sidx, string sord, int page, int rows, bool _search, string filters)
{
//load data from somthing,
IQuerable<Object> results = database.getresults //whatever you want to populate a set of data really
int totalRecords = results.Count();
var pagedResults = results.OrderBy(sidx + " " + sord).Skip((page -1) * rows).Take(rows);
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
rows = (
from tempValue in pagedResults.ToList()
select new
{
cell = new string[] {
tempValue.ColumnOneValue,
tempValue.ColumnTwoIntValue.ToString(),
//Etc
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}//ActionName
That would be a very basic way to display a jqGrid and then dynamically interact with it after other actions/events. enter code here
After much struggling here is what I did.I have a main view and a partial view. Initially the main view does not contain the partial view. When data is submitted , the partial view is loaded.
MyReport.cshtml
#{
ViewBag.Title = "Report";
}
<h2>Report</h2>
<br />
#using (Ajax.BeginForm("GetReportData", new AjaxOptions { UpdateTargetId = "result", HttpMethod = "Post", InsertionMode = InsertionMode.Replace}))
{
<div class="editor-label">Start Date</div>
<div class="editor-field">#Html.Editor("StartDate", "DateTime")</div>
<div class="editor-label">End Date</div>
<div class="editor-field">#Html.Editor("EndDate", "DateTime")</div>
<input type="submit" value="Submit" />
}
<div id="result">
</div>
Then I have a partial view of the Grid- MyReportPartial.cshtml
#model MyGridModel
#using Trirand.Web.Mvc
<link href="#Url.Content("~/Content/theme/ui.jqgrid.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="#Url.Content("~/Scripts/trirand/i18n/grid.locale-en.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/trirand/jquery.jqGrid.min.js")"></script>
<br />
#Html.Trirand().JQGrid(Model.Grid, "ReportGrid")
My Controller has the following
public ActionResult MyReport()
{
var gridModel = new Models.Grid.EmpHeadcountGridModel();
var grid = gridModel.MyGrid;
SetupHeadCountGrid(grid, DateTime.Now.ToShortDateString(), DateTime.Now.ToShortDateString());
return View(gridModel);
}
public ActionResult GetReportData(string startdate ,string enddate)
{
var gridModel = new Models.Grid.MyGridModel();
var grid = gridModel.EmpHeadcountGrid;
SetupHeadCountGrid(grid,costcenterid,startdate,enddate);
return PartialView("MyReportPartial",gridModel);
}
private void SetupHeadCountGrid(JQGrid grid,int costcenterid,string startdate,string enddate)
{
grid.ID = "ReportGrid";
grid.DataUrl = Url.Action("GetHeadcountData") + "?startdate=" + startdate + "&enddate=" + enddate;
}
public JsonResult GetHeadcountData(string startdate, string enddate)
{
DateTime startdt = DateTime.Parse(startdate);
DateTime enddt = DateTime.Parse(enddate + " 23:59:59");
var gridModel = new Models.Grid.MyGridModel();
var query= { soem query using date criteria}
gridModel.MyGrid.DataSource = query;
return gridModel.MyGrid.DataBind();
}
I have got a total product page which shows the total amount of the products added to the basket , What I want to do is to add a promo text field where users can add the promo code to get certain discounts , the promo code are save in the database with discount rate. So if a client enters the code , and press the promo button the system should check for the valid promo code and then do instaneous calculation by deducting the total price with the discount rate . Is this can be done using jQuery Ajax or is there any other possible solution for it , Any help or tutorial will be highly appreciated. Cheers
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#promo").change(function () {
var $this = $(this);
var number = $('promoNumber').val();
$.ajax({
url: '/Booking/Review',
type: "POST",
data: {number:textbox},
success: function (data) {
if (data["success"]) {
alert(data)
}
}
});
});
});
</script>
<%using (Html.BeginForm())
{ %>
<table>
<tr>
<td> <input type="button" id="promo" value="Promo" /> </td>
<td> <%: Html.TextBox("promoNumber") </td>
</tr>
<tr><td>
<div class="totalCost">
<label><b>Total Amount:</b></label> <%: String.Format("{0:c}", ViewBag.TotalAmount)%> <br /></div>
</td></tr>
</table> }%>
Controller
[HttpPost]
public ActionResult Review(int number)//this parameter is my selected checkbox value.I have to get this value from ajax
{
IVoucherRepository voucherResp = new VoucherRepository();
IQueryable<Voucher> getVoucher = voucherResp.GetVouchers(number);
//first check if the code is there or not else return error
int discount = 0;
foreach (var number in getVoucher)
{
discount = number.discount;//Thats the discount number
}
//after getting the discount code i need to pass that to ViewBag.TotalAmount to do calculation
ViewData["Data"] = "success";
return View();
}
I've seen a problem when you're posting your data to the controller:
var number = $('promoNumber').val();
and then:
data: {number:textbox},
What is textbox?
You should refer to your promoNumber like this in jQuery:
var number = $('#promoNumber').val();
This is what I would do:
$(document).ready(function() {
$("#promo").click(function() {
$.ajax({
type: 'POST',
url: 'Booking/Review',
dataType: 'json',
data: { number: $("#promoNumber").val() },
success: function(data) {
if (data) {
alert(data.discount);
alert(data.totalAmount);
}
}
});
});
});
Since you're using a button I would use click event.
I am using jSon as a return object.
and this is the controller:
[HttpPost]
public ActionResult Review(int number)
{
IVoucherRepository voucherResp = new VoucherRepository();
IQueryable<Voucher> getVoucher = voucherResp.GetVouchers(number);
//first check if the code is there or not else return error
int discount = 0;
int totalAmount = 0;
foreach (var number in getVoucher)
{
discount = number.discount;//Thats the discount number
}
//after getting the discount code i need to pass that to ViewBag.TotalAmount to do calculation
return (Json(new { discount = discount, totalAmount = totalAmount }, JsonRequestBehavior.DenyGet));
}
in your controller you can do all the calculations and then return a json object with all the properties you want.
Attach a jQuery post event to the coupon button:
$('input[name="coupon"]').click(function() {
$.ajax({
type: 'POST',
url: myUrl,
data: {code: $('input[name="code"]').val()},
success: function(discount) {
/* logic here. may need to store the code and it's discount
if more than one code is allowed */
}
});
});
Like ghayes mentioned though, if there are existing solutions, use those. They will, most likely, have considered many situations unknown to you.