<ul>
#foreach (var item in Model.Users.Where(s => s.DepartmentId == 3))
{
<li>
#Ajax.ActionLink(item.UserName, "Index", new { item.Id }, new AjaxOptions() { HttpMethod = "Get" });
</li>
}
</ul>
How can ı get item.Id if i onclick item.username with javascript ?
I thought give to attribute to "li onclick".but i dont know there is better solution here or not ?
You could use a standard link and data-* attribute:
<ul>
#foreach (var item in Model.Users.Where(s => s.DepartmentId == 3))
{
<li>
#Html.ActionLink(
item.UserName,
"Index",
new { id = item.Id },
new { #class = "myLink", data_id = item.Id }
)
</li>
}
</ul>
and then in a separate javascript file:
$(function() {
$('.myLink').click(function() {
// get the id:
var id = $(this).data('id');
alert(id);
// now you can send the AJAX request
$.get(this.href);
// cancel the default action of the link
return false;
});
});
Related
I have problem when using bootstrap tab that included in ASP.NET Admin Template Siminta . Whenever I hit the next tap with postback event it will be back to the active tab. I try many solution but in vain. asp.net bootstrap Keep current active tab after post-back event
<ul class="nav nav-pills">
<li class="active">
<i class="fa fa-home"></i> Profile
</li>
<li>
<i class="fa fa-leanpub"></i> Education
</li>
</ul>
............
<div class="tab-content">
<div class="tab-pane fade in active" id="EmpProfile">
.........
</div
</div>
And the code in bootstrap :
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: previous
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active
.one($.support.transition.end, next)
.emulateTransitionEnd(150) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
var old = $.fn.tab
$.fn.tab = function ( option ) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
// $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
// e.preventDefault()
// $(this).tab('show')
// })
$('[data-toggle="tab"],[data-toggle="pill"]').click(function () {
$(this).parent().children('.active[data-toggle="tab"],.active[data-toggle="pill"]').removeClass('active');
$(this).addClass('active');
});
}(jQuery);
So, how can I fix it?
I followed this instruction, but it still does not work: Bootstrap Tabs Maintain Selected (Active) Tab on PostBack in ASP.Net ,using the same bootstrap version the difference is only I use the DataGrid with Paging , whenever I go to next tab, click the page of DataGrid then it goes back to Active Tab (the first one):
Adding :
<asp:HiddenField ID="TabName" runat="server" />
Then use this script:
<script type="text/javascript">
$(function () {
var tabName = $("[id*=TabName]").val() != "" ? $("[id*=TabName]").val() : "EmpProfile";
$('#Tabs a[href="#' + tabName + '"]').tab('show');
$("#Tabs a").click(function () {
$("[id*=TabName]").val($(this).attr("href").replace("#", ""));
});
});
</script>
Then, put the behind code:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
TabName.Value = Request.Form[TabName.UniqueID];
}
}
And I also not forget to add this :
protected void grdEmployee_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
grdEmployee.CurrentPageIndex = e.NewPageIndex;
TabName.Value = Request.Form[TabName.UniqueID];
BindGrid();
}
}
<!--Basic Tabs -->
<ul class="nav nav-pills">
<li class="active">
<i class="fa fa-home"></i> Profile
</li>
.............
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="EmpProfile">
<asp:UpdatePanel ID="updatePanelEmployee" runat="server">
<ContentTemplate>
<asp:Datagrid ID="grdEmployee" runat="server" ..................
</asp:Datagrid>
</ContentTemplate>
</asp:UpdatePanel>
It works!
I have this helper code
#helper GetTreeView(List<MvcTreeview.Models.Category> siteMenu, int parentID)
{
foreach (var i in siteMenu.Where(a => a.ParentID.Equals(parentID)))
{
<li>
#{var submenu = siteMenu.Where(a => a.ParentID.Equals(i.ID)).Count();}
#if (submenu > 0)
{
<span class="collapse collapsible"> </span>
}
else
{
<span style="width:15px; display:inline-block"> </span>
}
<span id="Category">
#i.CategoryName
<b></b>
</span>
#if (submenu > 0)
{
<ul>
#Treeview.GetTreeView(siteMenu, i.ID)
#* Recursive Call for Populate Sub items here*#
</ul>
}
</li>
}
}
and i want to pass the id to a Action method of a controller.
How to pass the id from view to a action method in controller.
$('#Category').click(function () {
url = '#Url.Action("Index", "TestDetails");
$.ajax({
url: url,
type: 'POST',
success: function (returnData) {
},
error: {
}
});
});
How can i get the id in the second snippet of code.
Using that id i have to fetch some details using a action method in my controller.
Action Method
public ActionResult Index(int id)
{
TestDetail detail = new TestDetail();
detail = db.TestDetails.Single(a => a.ID == id);
return View(detail);
}
simply pass "this" to your onclick function
<span class="Category">
#i.CategoryName
<b></b>
</span>
Javascript: (Edited)
<script type="text/javascript">
function CategoryClick(clicked_id)
{
alert(clicked_id);
url = '#Url.Action("TestDetails", "Index")'; //Url.Action(actionName, ControllerName)
$.ajax({
url: url,
data: {id: clicked_id}, //json format
success: function (returnData) {
},
error: {
}
});
}
</script>
Edit your helper as following:
#helper GetTreeView(List<MvcTreeview.Models.Category> siteMenu, int parentID)
{
foreach (var i in siteMenu.Where(a => a.ParentID.Equals(parentID)))
{
<li>
#{var submenu = siteMenu.Where(a => a.ParentID.Equals(i.ID)).Count();}
#if (submenu > 0)
{
<span class="collapse collapsible"> </span>
}
else
{
<span style="width:15px; display:inline-block"> </span>
}
<span >
<a class="Category" href="#" id="#i.ID">#i.CategoryName</a>
<b></b>
</span>
#if (submenu > 0)
{
<ul>
#Treeview.GetTreeView(siteMenu, i.ID)
#* Recursive Call for Populate Sub items here*#
</ul>
}
</li>
}
}
and the ajax call:
$('.Category').click(function () {
url = '#Url.Action("Index", "TestDetails")';
$.ajax({
url: url,
type: 'POST',
data: "{'id': " + $(this).attr("id") + "}",
success: function (returnData) {
},
error: {
}
});
});
I am trying to pass parameter from view to controller,
This is my View:
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#foreach (var pricedetails in ViewBag.PriceTotal)
{
<div style="text-align:center; clear:both ">
<h5 class="product-title">#pricedetails.Title</h5>
</div>
<div class="product-desciption" style="height:40px">#pricedetails.Descriptions</div>
<p class="product-desciption product-old-price"> #pricedetails.PricePoints</p>
<div class="product-meta">
<ul class="product-price-list">
<li>
<span class="product-price">#pricedetails.PricePoints</span>
</li>
<li>
<span class="product-save">Get This Free</span>
</li>
</ul>
<ul class="product-actions-list">
<input type="submit" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />
</ul>
</div>
}
}
my action method:
On submit it reaches the Action Method, but I am not able to get the PriceId for each Price
[HttpPost]
public ActionResult Index(int id=0) // here PriceId is not passed on submit
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Content("<script language='javascript' type='text/javascript'>alert('You are not elgible');</script>");
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('You are elgible');</script>");
}
return View("Index");
}
Url Routing:
routes.MapRoute(
name: "homeas",
url: "Index/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
May I know what wrong I am doing ?
Please use the following in your cshtml page
#foreach (var item in Model)
{
#Html.ActionLink(item.PriceDetails, "GetGift", new { priceID = item.priceID }, new { #class = "lnkGetGift" })
}
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a.lnkGetGift").on("click", function (event) {
event.preventDefault();
$.get($(this).attr("href"), function (isEligible) {
if (isEligible) {
alert('eligible messsage');
}
else
{
alert('not eligible messsage');
}
})
});
});
</script>
and in controller
[HttpGet]
public JsonResult GetGift(int priceID)
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
Please change your parameters according to the method param and price entity
Hope this helps.
I suggest you get rid of the Html.BeginForm(). Just leave the for...loop and define your "Get Gift" button like this:
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(pricedetails.PriceId))'" />
Then, at the bottom of the view file where the Get Gift button is located, define some JavaScript:
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("Index", "Home")',
data: { priceId: priceId },
contentType : "json",
success:function(data){
// Do whatever in the success.
},
error:function(){
// Do whatever in the error.
}
});
</script>
By using an ajax call to get the gift data, you don't have to submit anything. This makes things a lot easier in your case. Pressing the Get Gift button simply makes an ajax call.
I don't have time to try this out myself, but hopefully the above example should get you up and running.
EDIT:
I've managed to sneak in some time to come up with an example.
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var items = new List<int>();
items.Add(1);
items.Add(2);
items.Add(3);
return View(items);
}
public ActionResult GetGift(int priceId)
{
return RedirectToAction("Index"); // You'll be returning something else.
}
}
View
#model List<int>
#foreach (var price in Model)
{
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(price))" />
}
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("GetGift", "Home")',
data: { priceId: priceId },
contentType: "json",
success: function(data) {
// Do whatever in the success.
},
error: function() {
// Do whatever in the error.
}
});
}
</script>
Hope this helps you.
I think you should correct here
<input type="button" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />
How i can add active class to menu with angular with this case
html code
<div class="categories" ng-controller="CategoryController">
<ul class="menu">
<li ng-repeat="category in categories">
<a ng-click="sendCategory(category)">{{category.name}}</a>
</li>
</ul>
</div>
js code
myApp.factory('Categories', ['$http',
function ($http) {
return {
get: function (callback) {
$http.get('data/categories.json').success(function (data) {
callback(data);
})
}
}
}
]);
use this syntax:
<ul class="menu" ng-class="{classname: variableFromScope}">
Set this variable to true or false (to activate or disactivate your classname class) in your controller where it needed:
$scope.variableFromScope = true;
here is solution
html code
<ul class="menu">
<li ng-repeat="category in categories"><a ng-click="sendCategory(category)" ng-class="{ active: activePath=='/{{category.name}}' }">{{category.name}}</a>
</li>
</ul>
js code
`
myApp.controller('CategoryController', function ($scope, $route, $location, $http, Categories){
Categories.get(function (response) {
$scope.categories = response;
});
$scope.sendCategory = function (category) {
$location.path(category.name);
};
$scope.activePath = null;
$scope.$on('$routeChangeSuccess', function () {
$scope.activePath = $location.path();
console.log($location.path());
});
})`
I'm working on my application that creates tabs dynamically and fills them with partial views using ajax.
My question is: how to load css for this views? What's the best way to do it? I mean I can't load the css file on the partial view (no head) or could i?
Some code: the tabManager (a partial view loaded on the main page):
<script>
var tabTemplate = "<li class='#{color}'><a id='#{id}'href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>"; // base format for the tabs
$(document).ready(function () {
var tabs = $("#tabs").tabs(); // apply jQuery ui to tabs
$("a.menuButton").click(function () {
var urlContent = $(this).data("direction");
var label = $(this).data("label");
var idTab = $(this).data("id");
var color = $(this).data("color");
var exist = false;
var counter = 0;
$('#tabs ul li a').each(function (i) { // tab already exist o no hay que crear una tabla?
counter = counter + 1; // index counter
if (this.id == "#" + idTab) { // Tab already exist?
exist = true;
$("#tabs").tabs("option", "active", counter - 1); //activate existing element
}
});
if (idTab == "-1") { // is a clickable element?
exist = true;
}
if (exist == false) { // create new tab
addTab(idTab, label, color); // basic tab
getTabContent(idTab, urlContent); // content for new tab
var lastTab = $('#tabs >ul >li').size() - 1; // get count of tabs
$("#tabs").tabs("option", "active", lastTab); // select last created tab
}
});
function getTabContent(idT, urlC) { // ajax call to partial view
$.ajax({
url: urlC,
type: 'GET',
async: false,
success: function (result) {
$("#"+idT).html(result);
}
});
};
function addTab(idT, labT, color) { //create new tab
var label = labT,
id = idT,
li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label).replace(/#\{id\}/g, "#" + id).replace(/#\{color\}/g, color)),
tabContentHtml = "Cargando...";
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'><p>" + tabContentHtml + "</p></div>");
tabs.tabs("refresh");
}
// close icon: removing the tab on click
tabs.delegate("span.ui-icon-close", "click", function () {
var panelId = $(this).closest("li").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
});
tabs.bind("keyup", function (event) {
if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
var panelId = tabs.find(".ui-tabs-active").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
}
});
});
</script>
<div id=tabs>
<ul>
</ul>
A button example:
<li><a class="menuButton" href="#" title="Permisos" data-id="tab3" data-direction="Permiso/_Administrar" data-label="Label" data-color="blue"><img src="#Res_icons.More">Permisos</a><li>
i found my answer here: http://dean.resplace.net/blog/2012/09/jquery-load-css-with-ajax-all-browsers/
the code:
<script type="text/javascript">
$(document).ready(function () {
$("head").append("<link href='...' rel='stylesheet'>");
});
</script>