jquery adding an onclick event to a href link - asp.net

i am converting over from websforms to asp.net mvc and i have a question.
i have a loop that generates links dynamicallly where picNumberLink is a variable in a loop and image is a variable image link.
i want to avoid putting javascript actions inline so in my webforms project is did the following:
hyperLink.Attributes.Add("onclick", "javascript:void(viewer.show(" + picNumberlink + "))");
what is the equivalent using jquery in asp.net mvc?
I have seen examples of using the $(document).ready event to attach on clicks but i can't figure out the syntax to pass in the picNumberLink variable into the javascript function.
suggestions?

EDIT: If you generate your links with the ID of this form:
<a id="piclink_1" class="picLinks">...</a>
<a id="picLink_2" class="picLinks">...</a>
<script type="text/javascript">
$('a.picLinks').click(function () {
//split at the '_' and take the second offset
var picNumber = $(this).attr('id').split('_')[1];
viewer.show(picNumber);
});
</script>

var functionIWantToCall = function(){
var wrappedLink = $(this);
//some serious action
}
//this should be called on document ready
$("#myLinkId").click(functionIWantToCall);
If you need to get URL of picture, keep it in anchor`s href:
var functionIWantToCall = function(event){
event.preventDefault(); //this one is important
var link = $(this).attr('href');
//some serious action
}

$(document).ready(function()
{
$('#LinkID').click(function() {
viewer.show($(this).attr('picNumber'));
});
});
You can add an attribute called picNumber to your hyperlink tag and set this is your mvc view
The link in your view might look something like this:
<%= Html.ActionLink("Index", new { id = "LINKID", picNumber = 1 }) %>

Assuming you're able to change the HTML you output, can't you put the picNumberLink in the id or class attribute?
HTML:
<img src="..."/>
jQuery:
$(function() {
// using the id attribute:
$('.view').click(function() {
viewer.show(+/-(\d+)/.exec(this.id)[1]);
});
// or using the class attribute:
$('.view').click(function() {
viewer.show(+/(^|\s)foo-(\d+)(\s|$)/.exec(this.className)[2]);
});
}}

Related

Can Ractive events work in markup rendered with the triple-stash syntax?

If I have the following in my Ractive template:
<span on-click='handleClick'>click me</span>
Then I can listen for the click with this:
app.on({
handleClick:function() {
alert("clicked!") ;
}
})
But lets say I have that same markup stored in a string variable called clicklyspan:
app.set("clicklyspan", "<span on-click='handleClick'>click me</span>")
and I render it in the template using the triple-stash syntax:
{{{clicklyspan}}}
The handleClick listener no longer gets fired. Is there anything I can do to force some kind of update to the rendered template so that the listener works? Say, after I do that app.set() call?
Here's a fiddle demonstrating the problem.
Thanks,
Dave
I have never used Ractive, but I did some research and it seems you have to use partials, like this:
var app = new Ractive({
el: 'container',
template: '#template',
data: {
myFunction: function() {
var template = '<a on-click="handleClick">I can now be clicked as well!</a>';
if (!this.partials.myFunction) {
this.partials.myFunction = template;
}
else {
this.resetPartial('myFunction', template);
}
return 'myFunction';
}
}
});
You will also need to use this instead of the triple mustache:
{{> myFunction() }}
Here's the corresponding jsfiddle.
Of course, replace myFunction with whatever name you like.
Related question I found useful:
RactiveJS events on tripple mustache

asp.net mvc3 - Loading a view always in a div

I am working on a mvc3 controller which loads a page on search. In the main index page, there is a search button and that loads another (details list) page in the given div.
I have incorporated pagination to the child view (details list). So, upon clicking on the "Next" link, it loads the next page.
cshtml of the index page: The flat id refers to where the details list loads.
<div id='FlatDetailcontainer'>Select a Project for Flat Details.. Loading...</div>
<script type="text/javascript" language="javascript">
// $(document).ready(function () {
function login() {
var check = document.getElementById("rad").value;
$("input[name=selectproj][value="+check+"]").attr('checked', true);
//document.getElementById("selectproj").checked = document.getElementById("rad").value;
if (check != "") {
handleprojselect(check);
}
}
function handleprojselect(myRadio) {
// document.getElementById("rad").value = myobj["proj"];
$.get('#Url.Action("Details", "ProjectDetails")?id=' + myRadio,
function (viewResult) {
$("#FlatDetailcontainer").html(viewResult);
});
}
function createproj() {
var url = '#Url.Action("Create")';
window.location.href = url;
}
</script>
The details page has the links of next and url action is as follows:
#if (Model.HasNextPage)
{
#Html.ActionLink("Next >", "Details", new { page = Model.PageNumber + 1 })
#Html.Raw(" ");
#Html.ActionLink(">>", "Details", new { page = Model.PageCount })
}
else
{
#:Next >
#Html.Raw(" ")
#:>>
}
However, this link always loads on a fresh page as there is no reference to the main Index page's div id. Please can someone suggest how to go ahead with this?
As far as you are loading part of the page via AJAX call you should also use AJAX to handle your pagination. You should create JS function like the following:
function nextPageClick(e)
{
e.preventDefault();
$.get($(this).attr("href"), //getting the URL from your link and loading the content via AJAX
function (viewResult) {
$("#FlatDetailcontainer").html(viewResult);
});
}
and bind it to the paging links on page load:
$(function (){
$('.nextPageLink').live('click', nextPageClick);
})
Notice that "live" jQuery method assigns click handler to the dynamically loaded content as well as on existing static content, so you have no need to reassing handler after each data reload.
You shoud add CSS class to your link to be able to locate it:
#Html.ActionLink("Next >", "Details", new { page = Model.PageNumber + 1, #class="nextPageLink" })
Of course you may use IDs or any other way to uniquely identify your pagination links.

Issue loading Mvc 4 view in Iframe? Not displaying the model properties in IFrame

I have this following requirement. Need to display the html Body of the Mime message in IFrame
View
<iframe id="myIframe1" src="http://localhost:23245/Home/GetMimeMessageContent?FilePath=D \MimeFiles/htmlBody-small1.eml&PartName=HtmlBody" style="width:600px;height:600px;" >
Controller
public ActionResult GetMimeMessageContent(string filePath,string partName)
{
var mimeModel = BuildMimeModel(filePath, partName);
MimeHeaderModel mimeHeadermodel = new MimeHeaderModel();
mimeHeadermodel.FromAddress = mimeHeadermodel.ToAddress = mimeHeadermodel.Subject = string.Empty;
mimeModel.MimeHeader = mimeHeadermodel;
return View("MailDetailsView", mimeModel.MimeBody.HtmlBody);
}
it's not showing the HtmlBody in the Iframe. But Its calling the controller. I dont know what I am missing.
Not sure if your using jquery or not, but:
$(function() {
var $frame = $('<iframe style="width:200px; height:100px;">');
$('body').html( $frame );
setTimeout( function() {
$.ajax(
url="/Home/GetMimeMessageType/small1.eml/HtmlBody",
type:'GET',
success: function(data){
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html(data);
}
);
},1 );
});
I have not tested the above code, but this should work fine. A few things to note:
You will need to create a custom Route to map this to your controller:
http://msdn.microsoft.com/en-us/library/cc668201(v=vs.100).aspx
You will also need to change the javascript $('body').html() to be the ID of a div as a placeholder
also you will notice i have no path, if this never changes, you should add the path to your code or you can use formcollection and change the jquery ajax to a post, and set the variables and values there.
Your content will then up up in an iframe.
Forget the whole html.renderaction, this solution gives you a little more scope

jQuery post from ASP.NET web page (WebMatrix)

I'm trying to submit form data with jQuery. I'm using ASP.NET WebMatrix. In a .cshtml file I have
#{
// other code
if(IsPost)
{
var item = new Item();
item.Title = Request.Form["title"];
item.Description = Request.Form["description"];
// aditional code here
}
}
<script type="text/javascript">
$(document).ready(function(){
$("form#itemForm").submit(function(){
$.post("form.cshtml", {
title: $("#title").val(),
description: $("#description").val(),
price: $("#price").val()},
function(data){
},
"json");
})
});
</script>
<form>
<!-- html form here -->
</form>
How can I pass values from form to Request.Form object? And how can I than response with json back to html?
A better way would be to just have jQuery post the form data using $(this).serialize() instead of building an object with all the values in it it to pass. After that, yah, Request["title"], etc will get the values that were posted.
This is what you want.
http://www.mikesdotnetting.com/Article/155/WebMatrix-And-jQuery-Forms
Values are passed through jQuery.post() to Request.Parameters.

Cannot select grid element through jQuery

This is a follow-up question to ASP.NET How to pass container value as javascript argument
Darin Dimitrov has kindly provided his answer using jQuery,
But for some reason, I was not able to select the grid row I wanted to.
Here is the jQuery used to select row.
$(function() {
$('#_TrustGrid input[name^=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
alert('Hello world = ' + index);
setGridInEditMode(index);
});
});
});
Here is the actual output HTML markup.
<input
id="_TrustGrid_ctl16_ctl05_ctl00_trustDocIDTextBox"
type="text" value="198327493"
name="_TrustGrid$ctl16$ctl05$ctl00$trustDocIDTextBox"/>
I have just started using jQuery tonight and been going through the official jQuery Selectors documentation but have been unsuccessful.
Am I missing something here?
What I did to save the full id of the control I used in my .aspx page:
<input type="hidden"
id="SubcontractorDropDownID"
value="<%= SubcontractorDropDown.ClientID %>" />
You can then just get the value of the id and then use that in your query to know which row to use.
At first glance, I think you just want a '$' instead of '^' and you should be targeting the ID and not the NAME in your selector?
$(function() {
$('#_TrustGrid input[id$=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
alert('Hello world = ' + index);
setGridInEditMode(index);
});
});
});
I do not know why selecting through #_TrustGrid would not work.
I was able to get around the problem by specifying :input as shown below.
$(function() {
//$('#_TrustGrid input[id$=trustDocIDTextBox]').each(function(index) {
$(':input[id$=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
alert('Hello world = ' + index);
setGridInEditMode(index);
});
});
});

Resources