MVC display partial view on navigation bar click - javascript

I want to display the partial view, when I click on navigation bar click. I have a view which contains left side menu. when user click on navigation bar item, appropriate view should display.
I am not getting how can I implement such view?
Manage.cshtml
<div class="row">
<div class="col-xs-12">
<div class="page-header">
<h1>My Account</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<ul class="nav nav-pills nav-stacked nav-stacked-extended">
<li class="active">
<a id="A3" target="_self" runat="server" href="#Url.Action("Contactinfo", "Account")">Contact Info</a>
</li>
<li class="">
<a id="A4" target="_self" runat="server" href="#Url.Action("changePassword", "Account")">Password</a>
</li>
</ul>
</div>
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
#Html.Partial("Contactinfo")
</div>
</div>
</div>
In above code, I have created left side menu i.e contactinfo, changepassword etc. when Manage.cshtml load first time I want to display Contactinfo view. When user click on password menu, contactinfo get's changed with changedpassword page. Please check following screen shot.
Here in above image you can see left side menu and appropriate page. What I want when user click on password, view changed to password page. Currently it shows contact info page. How can I do this?

i think you should render partial through JavaScript.
Let's say you have <div id="partialView"></div>
Then you should run Ajax query when user clicked on link.
Something like:
$.ajax({
url: $(this).data('yourUrl'),
type: 'GET',
cache: false,
success: function(result) {
$('#partialView').html(result);
}
});

Took me a little while to figure this out too.
Essentially, you want your Controller action to return a partial view, then use Ajax to load that returned partial view.
JavaScript / Ajax
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'POST',
data: { 'viewName': 'password' },
success: function (data) {
$('#partial-container').html(data);
}
});
Controller return type
Public ActionResult GetView(string viewName)
{
return PartialView(viewName, model);
}
Ideally, change your HTML so it's easier to reference the div container where you'd like to load the partial
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
<div id="partial-container">#Html.Partial("Contactinfo")</div>
</div>
</div>

In your requirement just make partial Views of the links present in your left side bar and when user clicks on a specific option in left side bar then just load a appropriate partial view from ajax call using jquery and just replace html of right side bar with the html coming from ajax call.
Give your left side menues unique id and then :
A Demo :
$(document).ready(function(){
$("#menu1").click(function(e){
e.preventDefault();
$.ajax({
url: "/MyController/getdata",
type: 'GET',
datatype: 'html',
data: { },
success: function (data) {
$("#div1").html('');
$("#div1").html(data);
});
});
});
Controller(MyController) :
[HttpGet]
Public ActionResult getdata(string dropval)
{
//bind model here
return PartialView("mypartialview",model)
}

try This JS for Clickevent
$(document).on('click', '#anCalcBtn', function () {
$('#anCalcDetail').load('/Home/Contactinfo/');
});
If I am not wrong you are trying to do like This

Related

How to pass the values to the other html page and redirect the to that page for onclick thumbnail using jquery?

Here I need to click on a thumbnail, so that it will show the details on other page, it should show the details of that particular thumb only. I used xml file here to fetch the data and display thumbnail. I am unable to pass the values to other page and open it at the same time onclick event. pls help
<div class="container-page">
<div class="row" id="portfolio">
<div class="col-md-2">
<nav>
<ul class="nav nav-pills nav-stacked" id="test">
<li role="presentation" class="active">Services</li>
<li role="presentation">Desktop</li>
<li role="presentation">Web</li>
<li role="presentation">Mobile</li>
<li role="presentation">Design</li>
</ul>
</nav>
</div>
<div class="col-md-10">
<div class="row" id="thumb">
</div>
</div>
</div>
</div>
<!-- js -->
$.ajax({
type:"GET",
url:"portfolio.xml",
dataType:"xml",
success:function(xml)
{
$(xml).find('thumbnail').each(function()
{
var $thumbnail=$(this);
var type=$thumbnail.find('type').text();
var descr=$thumbnail.find('description').text();
var title=$thumbnail.attr('title');
var imageurl=$thumbnail.attr('imageurl');
var thum='<div class="col-xs-6 col-md-3"> </div>';
thum=$(thum).appendTo("#thumb");
thum = $('').appendTo(thum);
var thumName = $('<div class="thumTitle"></div>').appendTo(thum);
$('<h2>'+title+'</h2>').appendTo(thumName);
$('<p>'+type+'</p>').appendTo(thumName)
thum = $('<img src="'+imageurl+'" alt="image" class="thumbImgSize imgSlide">').appendTo(thum);
$(".forHove").mouseup(function()
{
//here is the redirection code, and want to pass $thumbnail to testxml.html page
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
});
}
});
Well, one of the alternative is using Web Storage API.
Just store img html and use it.
// use 'click' instead of 'mouseup'
$(".forHove").click(function()
{
// store image html to sessionStorage
window.sessionStorage.image_data = $thumbnail.clone().wrapAll("<div>").parent().html();
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
// in http://www.bookmane.in/skillworks/testxml.html
// You have data sotred and insert it somewhere
$(document.body).append(window.sessionStorage.image_data);
You can achieve this thing using the following steps:
Add a form tag like
<form action="YOUR_PATH" method="GET">
<a class="thubnailClick" href="#" >
<html_of_your_thumbnail>
<input type="text" name="NAME_OF_PARAMETER" />
</a>
</form>
Now override the click event of <a> tag with
$(document).ready(function() {
$(".thubnailClick").on('click', function(event) {
// to override the default behavior of <a> tag.
preventDefault();
// Find the form element using closest() of jQuery.
// Call submit event of that form using $(form_element).submit();
});
})
Now on the other page you can get parameter from URL using location.search or follow:
Getting Query params using JavaScript
Now use these Params according to your needs.

How to get a listview to refresh with new data from a Kendo datasource

How do I get my list view page to refresh when I load new data into my kendo.data.DataSource?
I'm working on a Hybrid Mobile app using Telerik AppBuilder.
I have a simple listview that is bound to a data source.
I use an ajax POST request to load some JSON,
then place it in the datasource.
I have two pages, home and list view.
The home has some anchors that lead to a single list view page,
but with different data id values to produce different lists.
The first time I the list view page it loads correctly.
After that, the list view does not refresh when I reload the datasource;
the contents of the first list always display no matter what data id value I send in.
Here is the source:
JavaScript
window.APP =
{
blamListSource: null,
home:
{
fetchBlam: function(event)
{
var argumentData = event.button.data();
var requestBody =
{
"requestVersionId": "1",
"blamId": argumentData.id.toString()
};
$.ajax(
{
url: getBlamURI,
type: "POST",
data: JSON.stringify(requestBody),
dataType: "json",
contentType: 'application/json',
success: function(requestData, textStatus, jqxhr)
{
APP.blamListSource = new kendo.data.DataSource(
{
data: requestData.userList,
});
APP.blamListSource.read();
app.navigate("views/blamlist.html");
},
error: function(jqxhr, textStatus, error)
{
alert("Error");
},
});
}
}
};
home.html
<div data-role="view" data-title="Home" data-layout="main"
data-model="APP.models.home" data-zoom="true">
<div id="form-blam" data-role="content">
<a id="commercial" data-role="button"
data-bind="click: fetchBlam" data-id="27">Something</a>
<a id="personal" data-role="button"
data-bind="click: fetchBlam" data-id="39">Something Else</a>
</div>
</div>
views/blamlist.html
<div data-role="view" data-title="Blam List" data-layout="main"
data-model="APP" data-zoom="true">
<div data-role="navbar">
<a class="nav-button" data-align="left" data-role="backbutton">Back</a>
</div>
<ul id="blam-listview" data-style="inset" data-role="listview"
data-template="blamListTemplate" data-bind="source: blamListSource">
</ul>
<p id="no-contactlist-span" hidden="hidden" class="no-items-msg">
<b>No blam.</b>
</p>
</div>
<!-- Blam ListView Template -->
<script type="text/x-kendo-template" id="blamListTemplate">
<div>
<div>
<img id="blamPhoto" src="#: data.photoUri #"/>
</div>
<div>
<div id="name">#: data.name #</div>
<div>#: data.title #</div>
<div>
<div>
<a data-role="button" class="callimg"
data-phone="#: data.phone #" href="tel:#: data.phone #"
data-rel="external"></a>
</div>
<div>
<a data-role="button" class="emailimg"
href="mailto:#: data.email #"
data-rel="external"></a>
</div>
</div>
</div>
</div>
</script>
It appears to be fairly easy.
Add data-reload="true" to the view.
Old - does not refresh
<div data-role="view" data-title="Blam List" data-layout="main"
data-model="APP" data-zoom="true">
New - refreshes
<div data-role="view" data-title="Blam List" data-layout="main"
data-model="APP" data-zoom="true" data-reload="true">
Edit I accidentally put "data-refresh", which is wrong. The correct value (edited to be correct) is "data-reload".

show records on same details page by clicking next button in asp.net mvc getting error

I want to display the records on details page when user click on next button then he should be able to display the next record of table. Suppose user select the details of a particular record id 1 he get the details of that id 1 at the same time on the same page by clicking the next button user should be able to get the record of id 2 and vice versa. I have done it but getting some error when table has no such id named id 3 after id 1 and id 2 its showing me the error. Please help me to find out where i am wrong.
View
#model WebApp.ViewModels.ViewTeamList
<script type="text/javascript">
var dataid = '#Html.Raw(Json.Encode(Model.TeamDetails.TeamId))';
for( var item in dataid)
console.log(dataid[item]);}();
</script>
<script type="text/javascript">
$("#btnNext").click(function () {
var $buttonClicked = $(this);
var nid = $buttonClicked.attr('data-id');
console.log(nid);
$.ajax({
url: 'Team/Next',
data: { dataid: nid },
//data: JSON.stringify(data.TeamId),
success: function (response) {
divDetail.html(data);
}
});
});
</script>
<div class="row">
<div class="col-md-11 col-sm-11 pull-left" style=" font-size:large; font-weight:600">
#Model.TeamDetails.TeamName
</div>
#* <div class="col-md-1 col-sm-1 pull-right">*#
<div class="navi-but">
<a href="#" id="btnPrevious" data-id="#Model.TeamDetails.TeamId" class="details">
<span class="previous">Previous</span>
</a>
<a href="#" class="details" data-id="#Model.TeamDetails.TeamId" id="btnNext">
<span style="padding-right:7px">Next</span><span class="next"></span>
</a>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="~/Images/settings.png" />
</a>
<ul class="dropdown-menu" role="menu">
<li>Edit</li>
</ul>
</li>
</div>
#* </div>*#
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
#Html.CustomLabel("lblTeam","CT Team Name:")
</div>
<div class="col-md-8 col-sm-8">
#Model.TeamDetails.TeamName
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
#Html.CustomLabel("lblDescription","Description:")
</div>
<div class="col-md-8 col-sm-8">
#Model.TeamDetails.Description
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
#Html.CustomLabel("lblCTUserCount","User Count")
</div>
<div class="col-md-8 col-sm-8 pull-left">
#Model.TeamDetails.UserCount
</div>
</div>
Controller
public ActionResult Next(int dataid)
{
dataid++;
ViewTeamList viewTeamList = new ViewTeamList();
viewTeamList.ViewTeamDetails(dataid);
return PartialView("_ViewTeamDetails", viewTeamList);
}
View model
public class ViewTeamList
{
public TeamDetails TeamDetails;
private ITeamService teamService;
public ViewTeamList()
{
}
public void ViewTeamDetails(int Id)
{
teamService = new TeamService(pDbContext);
TeamDetails = teamService.GetTeamDetails(Id);
//return (TeamDetails.First());
}
}
Please help where i am doing wrong.
I didn't look your code in detail but it seems to me that you have a logical problem. Since you are always incrementing id by one ( dataid++; ) that won't work if some record is deleted in the meantime. For example let's say that you have Record1 with id 1, Record2 with id 2 and Record 3 with id 3 and you delete Record2. Now when you are trying to get next record after Record1 you are incrementing id by 1 so you have 2 and there is no record with id 2 in the db anymore.
Instead of dataid++; you should find next id that really exists in db. As I said I didn't read code in detail so there may be more possible problems.
To Display from WebMethod You Should follow these steps:
create
[webmethod]
to retrieve all the data
List items then make a javascript method in client side use:
ajax({ type:'post', url:'exaple.aspx/showMethod', data:{}, datatype:'json', contentType:'application/json; charset=utf-8',
scuccess:function(data) --display from here in table or any other
data ), error:function(){ alert('Error'); } })

Possible reasons why SPA application views won't communicate with JavaScript

So I have a bit of a mindboggler on my hands that's refusing to bend. My objective is to log on a database every single time a page is visited. I have created on the c# side code that logs this info and I know it works. What I'm trying to do now is relatively straightfoward; every time an item (that is, a page) is clicked on the home view list (which acts as a shell for the SPA and doesnt change), send the page name to a function in Javascript which will in turn communicate to the Webmethod. The problem is, when the app starts, as it is a SPA, it collects all the divs (see below) and renders them and for some reason, it does not want to communicate and pass parameters into the javascript function, no matter where I put it (I've put it on a header, I've put it underneath the html, etc). The onclick function works fine when test it separately, but in this application, it refuses to work.
I've also tried using 'body onload="PostName();" as well as window.onload on each of the pages to invoke the function but its also a blank. Some thoughts on where the problem might be?
<tr class="row">
<td>
<div class="tabbable">
<ul class="nav nav-tabs nav-stacked" id="menuTabs">
<li class="active">Home</li>
<li class="">Tutuwa roadshows</li>
<li class="">FAQ's and presentations</li>
<li class="">Example scenarios</li>
<li class="">Financial advisors</li>
<!--<li class="">Private Clients</li>-->
<li class="">Trust deeds</li>
<li class="">Newsflashes</li>
<li class="">Useful links and contacts</li>
<li class="">Webinar</li>
</ul>
</div>
<div class="newsflash">Click here for the latest newsflash.</div>
</td>
<td rowspan="2">
<div class="tab-content">
<div class="tab-pane active" id="land">#Html.Partial("Land")</div>
<div class="tab-pane" id="tutuwaroadshow">#Html.Partial("TutuwaRoadshow")</div>
<div class="tab-pane" id="faqsandpresentations">#Html.Partial("FaqsAndPresentations")</div>
<div class="tab-pane" id="examplescenarios">#Html.Partial("ExampleScenarios")</div>
<div class="tab-pane" id="financialadvisors">#Html.Partial("FinancialAdvisors") </div>
<div class="tab-pane" id="privateclients">#Html.Partial("PrivateClients")</div>
<div class="tab-pane" id="trustdeeds">#Html.Partial("TrustDeeds")</div>
<div class="tab-pane" id="newsflashes">#Html.Partial("NewsFlashes")</div>
<div class="tab-pane" id="usefullinksandcontacts">#Html.Partial("UsefulLinksAndContacts")</div>
<div class="tab-pane" id="webinar">#Html.Partial("Webinar")</div>
</div>
</td>
</tr>
</table>
the function, currently sitting on the header:
<head>
<script type="text/javascript">
function PostName(pageName) {
debugger;
//String PageName = "ExampleScenarios";
$.ajax({
type: "POST",
url: 'HomeController/SaveVisitorHits',
data: { s: pageName },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//do nothing
},
error: function (e) {
// do nothing
}
});
}
</script>
<title></title>
</head>
Note that when I seperate this code from the app, it works fine (see http://jsfiddle.net/cLp6y51c/ as was created by another user who was trying to help earlier on). The problem is within the application, maybe some sort of setting that I'm not aware of.
This is the alternate method I've tried on each of the pages but also doesnt work:
<header>
<img src="../../content/images/examplescenarios-header.jpg" style="height: 340px" />
<script type="text/javascript">
function PostName() {
debugger;
//String PageName = "ExampleScenarios";
$.ajax({
type: "POST",
url: 'HomeController/SaveVisitorHits',
data: { s: "ExampleScenarios" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//do nothing
},
error: function (e) {
// do nothing
}
});
}
window.onload = PostName;
</script>
</header>
<body onload="PostName();">
It looks like you are making a call to a wrong URL. I presume it is a .NET MVC app? In .NET MVC you don't put the word Controller in the URL. The URL should be Home/SaveVisitorHits

Load JSON data into a Bootstrap modal

I want to load a JSON file that creates a list inside a Bootstrap Modal. I have it set where if you click on a person's picture, the modal pops up.
<li class="project span3" data-type="pfa">
<a data-toggle="modal" data-target="#myModal" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
Here's an example of the JSON data:
var florida_exoneration = [
{
"last_name":"Atkins",
"first_name":"Kenneth",
"age":16,
"race":"Caucasian",
"state":"FL",
"crime":"Sexual Assault",
"sentence":"10 years",
"conviction":2004,
"exonerated":2008,
"dna":"",
"mistaken witness identification":"",
"false confession":"",
"perjury/false accusation":"Y",
"false evidence":"",
"official misconduct":"",
"inadequate legal defense":"",
"compensation":""
}
]
I'd like the modal to display something like this inside the box:
Title = "first_name + last_name"
Age = "age"
Race = "race"
State = "state"
""
""
I also want to make sure the data is tied to the picture so the modal doesn't get confused. I'm sorry if this is a bit confusing. I'll try and clarify if anyone has any questions.
Method 1: using Ajax
Every time a user clicks an image, you get the id from the clicked image and then you send an Ajax request to server in order to get the JSON object.
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" data-id="2" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
$.ajax({
type: "GET",
url: 'getJson.php?id='+$(this).data('id'),
dataType: 'json',
success: function(data){
htmlData = '<ul><li>title: '+data.first_name+'</li><li>age: '+data.age+'</li></ul>';
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
}
});
return false;
});
})(jQuery);
Method 2: using hidden div
No need to any Ajax request, but you need to create a hidden div that contain all the information you want to display in the modal
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
<div class="profile hide">
<ul>
<li>title: Atkins Kenneth</li>
<li>Age: 16</li>
</ul>
</div>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
htmlData = $(this).find('.profile').html();
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
return false;
});
})(jQuery);

Categories

Resources