I'm struggling in figuring out a way to get the content in one of my "tab-content" from an action other than my index
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
#Html.ActionLink("Analysis History", "Index", "Feedback", new { Tab = "Analysis" }, new { #class = "nav-link active" })
</li>
<li class="nav-item">
#Html.ActionLink("Pending Analysis Requests", "PendingList", "Feedback", new { Tab = "Pending" }, new { #class = "nav-link active" })
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade #(ViewBag.Hash == "Analysis" ? "show active" : "")" id="Analysis" role="tabpanel" aria-labelledby="Analysis-tab">
<div> .... </div> // WORKS FINE
</div>
<div class="tab-pane fade #(ViewBag.Hash == "Pending" ? "show active" : "")" id="Pending" role="tabpanel" aria-labelledby="Pending-tab">
<div>
//HERE I WANT THE RESULT FROM PENDINGLIST ACTION
</div>
</div>
</div>
Action
public async Task <IActionResult> PendingList (int AnalysisPage = 1, string Tab = "Pending")
{
ViewBag.Hash = Tab;
//POPULATING THE MODEL
return PartialView("_PendingAnlaysisRequestsList", model);
}
_PendingAnlaysisRequestsList partial is holding a table to display model content
ps: in index action I'm setting ViewBag.Hash and the whole action returns view()
Is using ajax the only solution or is there any other ways ?
any suggestions is appreciated !
In my opinion, I suggest you could use ajax and tab content to achieve your requirement, you could use ajax to load the view and generate the Hyperlink to show them.
More details, you could refer to below codes:
Notice: You should replace the ajax url with your own url.
<div>
<ul class="nav nav-tabs justify-content-center">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" role="tab" aria-controls="Analysis" id="Analysislink"
href="#Analysis">Analysis</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" role="tab" aria-controls="Pending" id="Pendinglink"
href="#Pending">Pending</a>
</li>
</ul>
</div>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="Analysis" role="tabpanel" aria-labelledby="Analysis-tab">
</div>
<div class="tab-pane fade" id="Pending" role="tabpanel" aria-labelledby="Pending-tab">
</div>
</div>
#section scripts
{
<script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.js"></script>
<script>
$("#Analysislink").click(function () {
$.ajax({
url: "/Staff/Onboarding/StaffDetails?StaffID=#Model.StaffID",
type: "get",
success: function (result) {
$("#Analysis").html(result);
}
})
});
$("#Pendinglink").click(function () {
$.ajax({
url: "/Staff/Onboarding/Biodata",
type: "get",
success: function (result) {
$("#Pending").html(result);
}
})
});
$(function () {
$.ajax({
url: "/Staff/Onboarding/StaffDetails?StaffID=#Model.StaffID",
type: "get",
success: function (result) {
$("#Analysis").html(result);
}
})
})
</script>
}
Result:
I've solved it simply by the following modifications:
PendingList Action
public async Task <MyIndexModel> PendingList (int AnalysisPage, string Tab)
{
ViewBag.Hash = Tab;
//POPULATING THE MODEL
return model;
}
Index Action:
if(Tab == "Analysis")
{
//POPULATING THE MODEL WITH DEFFERENT DATA
}
if(Tab == "Pending")
{
model = PendingList(AnalysisPage,Tab).Result;
}
View:
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
#Html.ActionLink("Analysis History", "Index", "Feedback", new { Tab = "Analysis" }, new { #class = "nav-link active" })
</li>
<li class="nav-item">
#Html.ActionLink("Pending Analysis Requests", "PendingList", "Feedback", new { Tab = "Pending" }, new { #class = "nav-link active" })
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade #(ViewBag.Hash == "Analysis" ? "show active" : "")" id="Analysis" role="tabpanel" aria-labelledby="Analysis-tab">
<div> .... </div> // WORKS FINE
</div>
<div class="tab-pane fade #(ViewBag.Hash == "Pending" ? "show active" : "")" id="Pending" role="tabpanel" aria-labelledby="Pending-tab">
<div>
//HERE I LISTED THE RESULT IN A TABLE
</div>
</div>
</div>
Best Regards
Related
Update: As requested added extra code and error info.
I have seen many versions of this same error being asked and answered but not for the exact issue I have.
So I have an ASP.NET MVC app that has a BaseViewModel class, from which all other view models inherit, and is used in the layout.cshtml file.
I am adding a new view that needs to display a list of items pulled from a database. So the standard thing to code was to load a list of the new view model and send it to the new view and the view would add a new row to a table for every item in the list. This works fine without referencing to layout file. But when I add the reference like the below:
#model IEnumerable<EnrollmentMonitor.ViewModels.SystemListViewModel>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "System Index";
}
It throws this error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[EnrollmentMonitor.ViewModels.SystemViewModel]', but this dictionary requires a model item of type 'EnrollmentMonitor.ViewModels.BaseViewModel'.
I understand fundamentally what is going on but I am not sure what the best way to fix this is. Is there a way without completely redesigning my model code?
I have tried making a SystemModel class that has the elements I need (this is what was in SystemListViewModel before:
using System.ComponentModel.DataAnnotations;
namespace EnrollmentMonitor.ViewModels
{
public class SystemModel
{
public int ID { get; set; }
[Required(ErrorMessage = "System is required")]
public string System { get; set; }
[Display(Name = "Is Active?")]
public string IsActive { get; set; }
}
}
Then I made SystemListViewModel just have a single property that is a List of SystemModel:
using System.Collections.Generic;
namespace EnrollmentMonitor.ViewModels
{
public class SystemListViewModel : BaseViewModel
{
public List<SystemModel> Systems { get; set; }
}
}
My view now just takes the SystemListViewModel without the IEnumerable:
#model EnrollmentMonitor.ViewModels.SystemListViewModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "System Index";
}
<h2>Systems</h2>
<p>
#Html.ActionLink("Create New", "NewSystem") | #Html.ActionLink("Configuration List", "ConfigurationIndex")
</p>
<table class="table">
<tr>
<th>
System Name
</th>
<th>
Is Active?
</th>
<th></th>
</tr>
#foreach (var item in Model.Systems)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.System)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsActive)
</td>
<td>
#Html.ActionLink("Edit", "EditSystem", new { id = item.ID }) |
#if (item.IsActive == "Active")
{
#Html.ActionLink("Disable", "DisableSystem", new { id = item.ID },
new { onclick = "return confirm('Are you sure you wish to disable this item?');" })
}
else
{
#Html.ActionLink("Enable", "EnableSystem", new { id = item.ID },
new { onclick = "return confirm('Are you sure you wish to enable this item?');" })
}
</td>
</tr>
}
</table>
And lastly this is the layout file with some code redacted for security reasons:
#using EnrollmentMonitor.ViewModels
#model BaseViewModel
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#Model.Title</title>
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/fontawesome/css")
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/prettify")
#Scripts.Render("~/bundles/chart")
#RenderSection("scripts", required: false)
#*<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">*#
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="alert alert-danger" id="browerwarning" style="display:none"><center><b>Warning: You are using an outdated browser which is not supported.</b><br />Please use browsers supported by Aflac such as Google Chrome or Microsoft Edge.</center></div>
<div class="body-content">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Enrollment Monitor", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
#if (Model.IsAuthorized("XX"))
{
<li>#Html.ActionLink("Transaction Summary", "TransSummary", "TransSummary")</li>
<li>#Html.ActionLink("Associate Search", "AgentSearch", "AgentSearch")</li>
}
<li class="dropdown dropdown-large">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
Reports & Tools
<b class="caret"></b>
</a>
<ul class="dropdown-menu dropdown-menu-large row">
#if (Model.IsAuthorized("XX"))
{
<li class="col-sm-4">
<ul>
<li class="dropdown-header">Transaction Reports</li>
<li>Transaction Details Report</li>
<li>PDF Guid Report</li>
<li>Policy Detail Report</li>
<li>Policy by Employee Name</li>
#if (Model.IsAuthorized("XX"))
{
<li>Error Report</li>
}
#if (Model.IsAuthorized("XX"))
{
<li>Error Report By Error Message</li>
}
<li class="divider"></li>
<li class="dropdown-header">Associate Info Report</li>
#*<li>Transaction by Writing Number</li>*#
<li>Agent Details</li>
#if (Model.IsAuthorized("XX"))
{
<li>Agent License Information</li>
<li>Agent Training</li>
<li>Agent Appointment</li>
}
</ul>
</li>
}
#{var col = "12";
if (Model.AuthorizedAs("XX")) { col = "6"; }
if (Model.IsAuthorized("XX")) { col = "4"; }
}
<li class="col-sm-#col">
<ul>
<li class="dropdown-header">Productions Reports</li>
<li>Policy Count by Channel</li>
<li>New AP by Platform</li>
<li>Policy by State</li>
<li>Production Report</li>
<li>Transaction Volume Report</li>
<li class="divider"></li>
<li class="divider"></li>
<li>Miscellaneous Reports</li>
</ul>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown " style="background-color:ButtonFace">
#Model.Env <b class="caret"></b>
<ul class="dropdown-menu">
<li>Production</li>
<li>System Test</li>
<li>Integration</li>
<li><a herf="#" onclick="return changeenv('dev');">Development</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="body-content" id="body">
#RenderBody()
<hr />
<footer>
<div class="body-content">
<ul class="nav navbar-nav">
<li class="text-muted">Last Update: #Model.CurrentTime</li>
</ul>
<ul class="nav navbar-right">
<li class="text-muted">Login As: #Model.UserID Level: #Model.SecurityLevel</li>
</ul>
</div>
</footer>
</div>
<script type="text/javascript">
changeenv = function (env) {
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
if (env == 'dev')
window.location.href = '#Model.MonitorURL("dev")' + pathname;
else if (env == 'intg')
window.location.href = '#Model.MonitorURL("intg")' + pathname;
else if (env == 'syst')
window.location.href = '#Model.MonitorURL("syst")' + pathname;
else if (env == 'prod')
window.location.href = '#Model.MonitorURL("prod")' + pathname;
return false;
}
</script>
Now I had some issues at first because I forgot to update the controller but that did work. But I really didn't like it. So was there a better way?
I used this code with bootstrap 3, and it worked correctly, when clicking on the page, it appeared as active, but when switching to bootstrap 4, it no longer calls the active class, when I pass the page number inside the "for"
Any ideias how to resolve that?
<ul class="pagination">
<li class="page-item ">
#{
if (ViewBag.pageNumber> 1)
{
<a class="page-link" href="#Url.Action("Index", "Barcos", new { search= ViewBag.Search, pageNumber= ViewBag.pageNumber- 1 })">before</a>
}
else
{
<a class="page-link" href="#">
before
</a>
}
}
</li>
#{
var page = ViewBag.pageNumber;
for (var i = 1; i <= ViewBag.Count; i++)
{
<li #(page== i ? "class=page-item active" : "")>
<a class="page-link" href="#Url.Action("Index", "Barcos", new {search= ViewBag.Search, pageNumber= i})">#i</a>
</li>
}
}
<li>
#if (ViewBag.pageNumber< ViewBag.count)
{
<a class="page-link" href="#Url.Action("Index", "Barcos", new { Search= ViewBag.Search, pageNumber= ViewBag.pageNumber+ 1 })">Next</a>
}
else
{
<a class="page-link disabled" href="#">
Before
</a>
}
</li>
</ul>
You need class="page-item" on all list items, not just for your current page
Corrected bode below.
#for (var i = 1; i <= ViewBag.Count; i++)
{
var page = ViewBag.pageNumber;
string classes = "page-item";
if (page == i)
{
classes += " active";
}
<li class="#classes">
#Html.ActionLink(i.ToString(), "Index", "Barcos", new { search = ViewBag.Search, pageNumber = i }, new { #class = "page-link" })
</li>
}
This generates the following HTML
<ul class="pagination">
<li class="page-item ">
<a class="page-link" href="/Barcos/Index?pageNumber=1">before</a>
</li>
<li class="page-item">
<a class="page-link" href="/Barcos/Index?pageNumber=1">1</a>
</li>
<li class="page-item active">
<a class="page-link" href="/Barcos/Index?pageNumber=2">2</a>
</li>
<li class="page-item">
<a class="page-link" href="/Barcos/Index?pageNumber=3">3</a>
</li>
<li>
<a class="page-link" href="/Barcos/Index?pageNumber=4">Next</a>
</li>
</ul>
Single page having three different registration form,based on single ID reference, I need to call the three different [HttpPost] ActionResult method ,when i click the submit button for first form it's goes to first action result method correctly.
<div class="page-content">
<div class="container-fluid">
<header class="section-header">
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<h2>Company Registration Form</h2>
</div>
</div>
</div>
</header>
#using (Html.BeginForm(FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<section class="tabs-section">
<div class="tabs-section-nav tabs-section-nav-icons">
<div class="tbl">
<ul class="nav" role="tablist">
<li class="nav-item">
<a class="nav-link active" href="#tabs-1-tab-1" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="font-icon font-icon-cogwheel"></i>
Company Registration Form
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-2" role="tab" data-toggle="tab">
<span class="nav-link-in">
<span class="glyphicon glyphicon-music"></span>
Company Social Network
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-3" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="fa fa-product-hunt"></i>
Company Reference
</span>
</a>
</li>
</ul>
</div>
</div><!--.tabs-section-nav-->
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active show" id="tabs-1-tab-1">
<br />
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model =>Model.company.CompanyName, new { #class = "form-label semibold control-label" })
#Html.TextBoxFor(model => model.company.CompanyName, new { #class = "form-control", placeholder = "Enter the Company Name" })
#Html.ValidationMessageFor(model => model.company.CompanyName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.ShortName, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.ShortName, new { #class = "form-control", placeholder = "Enter the Short Name" })
#Html.ValidationMessageFor(model => model.company.ShortName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Division, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Division, new { #class = "form-control", placeholder = "Enter the Division" })
#Html.ValidationMessageFor(model => model.company.Division)
</fieldset>
</div>
</div><!--.row-->
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Email, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Email, new { #class = "form-control", placeholder = "Enter your Email" })
#Html.ValidationMessageFor(model => model.company.Email)
</fieldset>
</div>
</div><!--.row-->
</div>
</section>
<input type="submit" name="Submit" id="Save" value="Save" class="btn btn-rounded btn-inline btn-success" onclick=" GetInfo();" />
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-2">
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.FaceBookID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.FaceBookID, new { #class = "form-control", placeholder = "Enter the Facebook Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.TwitterID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.TwitterID, new { #class = "form-control", placeholder = "Enter the Twitter Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.linkedinID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.linkedinID, new { #class = "form-control", placeholder = "Enter the Linkedin Link" })
</fieldset>
</div>
</div><!--.row-->
</div>
</section>
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
<input type="submit" name="Submit" id="Save" value="Next" class="btn btn-rounded btn-inline btn-success" onclick="GetInfo1();" />
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-3">
Tab 3
<br /><br />
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
<input type="submit" name="Submit" value="Finish" class="btn btn-rounded btn-inline btn-success" />
</div><!--.tab-pane-->
</div><!--.tab-content-->
</section><!--.tabs-section-->
}
</div>
</div>
ActionResult Code:
[HttpPost]
public ActionResult AddCompany(MainModel cmp)
{
try
{
if (ModelState.IsValid)
{
}
return View();
}
catch
{
return View();
}
}
When i click second Submit button it's again going to the same ActionResult AddCompany(MainModel cmp) but i need to go to ActionResult AddSocial(MainModel Social)
Here this code :
[HttpPost]
public ActionResult AddSocial(MainModel Social)
{
try
{
if (ModelState.IsValid)
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), "paginationClickHandler", "paginationClickHandler();", true);
}
return View();
}
catch
{
return View();
}
}
Ajax Method:
function GetInfo() {
var company = { companyName: document.getElementById('CompanyName').value, shortName: document.getElementById('ShortName').value, division: document.getElementById('Division').value, Email: document.getElementById('Email').value }
$.ajax({
type: "POST",
url: "/Company/AddCompany",
data: '{cmp:' + JSON.stringify(company) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
function GetInfo1() {
var Social = { faceBook: document.getElementById('FaceBook').value, twitter: document.getElementById('Twitter').value, linkedin: document.getElementById('linkedin').value }
$.ajax({
type: "POST",
url: "/Company/AddSocial",
data: '{Social:' + JSON.stringify(Social) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
Your button is still inside a form. So when you handle your button click in javascript, you need to make sure to prevent the default behavior of a submit button click inside a form ( the form submit).
Using unobtrusive javascript way, give a unique id to your button
<input type="submit" id="saveSocial" value="Next" />
and now, bind click event on this button, prevent the default behavior using
jquery preventDefault method and call your js method.
$(document).ready(function() {
$("#saveSocial").click(function(e) {
e.preventDefault();
GetInfo1();
});
});
Also it does not make sense to return a full view from your action method when the call is from ajax code. May be you should return a json response.
A submit inside the form is going to post the form, even if you have an onclick action written. If you want it to instead call the javascript function, change the <input> to a <button> or <a> tag.
EDIT
Delete the form tag completely to prevent submission which is reloading your page.
I'm attempting to render a partial view in a Div within the carousel i have created on the home page. The partial view is from a different controller the view code is as seen below. The partial view contains a table which i want to be shown within the carousel div. Currently nothing is being loaded into the div with the code i'm using, i'm not sure what i'm doing wrong. You help would be much appreciated.
Home Index View
#{
ViewBag.Title = "Home Page";
}
<div id="mycarousel" class="carousel slide" data-ride="carousel" style="margin-top: 30px">
<ol class="carousel-indicators">
<li data-target="#mycarousel" data-slide-to="0"></li>
<li data-target="#mycarousel" data-slide-to="1" class="active"></li>
<li data-target="#mycarousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner" role="listbox">
<div class="item active">
<div id="dvgetpvt">
</div>
</div>
<div class="item">
<p>
NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.
</p>
</div>
</div>
<a class="left carousel-control" href="#mycarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#mycarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
Within the view code i have the following to get the partial view.
<script type="text/javascript">
$.ajax({
url: "/crmPVT/GetPVT",
contentType: "application/html; charset=utf-8",
type: "GET",
dataType: "html"
})
.success(function (result) {
$('#dvgetpvt').html(result);
})
.error(function (xhr, status) {
alert(status);
})
</script>
The crmPVT controller contains the following code for the partial view
crmPVT Controller
public PartialViewResult GetPVT()
{
var all = (from e in db.crmPVT
where e.Report_ID == 1
select e);
var commnorth = (from e in db.crmPVT
where e.Report_ID == 1 &&
e.Team.Contains("Commercial North")
select e);
var team = User.Identity.Name == "*****" ? commnorth : all;
return PartialView(team);
}
I have code sample like this
<div class="col-md-2 col-sm-3 col-xs-12 fill">
<div class="nav-highlight fill">
<ul class="list-group">
<li class="list-group-item borderless active">
<a class="" href="#login"><i class="fa fa-share-square-o" aria-hidden="true"></i>Login</a>
</li>
<li class="list-group-item borderless">
<a class="" href="#register"><i class="fa fa-pencil-square-o" aria-hidden="true"></i>Sign Up</a>
</li>
</ul>
</div>
I need to use ActionLink in MVC from a link and you can see i have class="active" i need when click on that will have that class,what i the best way to do?
Thanks all
$(document).ready(function(){
$('ul li a').click(function(){
$('li a').removeClass("active");
$(this).addClass("active");
});
});
body{
font-sze:14px;
}
.container{
max-width:960px;
margin:0 auto;
}
nav ul li{
list-style:none;
float:left;
padding-right:20px;
}
nav ul li a{
text-decoration:none;
color:#000;
background-color:#ccc;
padding:4px 5px;
}
.active{
background-color:#333;
color:#fff;
}
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<div class="container">
<nav>
<ul>
<li><a class="menu active" href="#">Menu1 </a></li>
<li><a class="menu" href="#">Menu2</a></li>
<li><a class="menu" href="#">Menu3</a></li>
<li><a class="menu" href="#">Menu4</a></li>
<li><a class="menu" href="#">Menu5</a></li>
</ul>
</nav>
</div>
</body>
You can use onclick attribute like this:
Replace a tags:
#Html.ActionLink("Login", "Your Action", null, new { onclick = "setActive(this);", #class = "" })
#Html.ActionLink("Sign Up", "Your Action", null, new { onclick = "setActive(this);", #class = "" })
Add setActive javascript function:
<script>
function setActive(element) {
element.parentElement.className = "list-group-item borderless active";
}
</script>