How can one call a javascript function in html.actionlink in asp.net mvc?
I want to call one method, which is in JavaScript, but how I call it within html.actionlink in the same page?
you need to use the htmlAttributes anonymous object, like this:
<%= Html.ActionLink("linky", "action", "controller", new { onclick = "someFunction();"}) %>
you could also give it an id an attach to it with jquery/whatever, like this:
<%= Html.ActionLink("linky", "action", "controller", new { id = "myLink" }) %>
$('#myLink').click(function() { /* bla */ });
For calling javascript in your action link you simply need to write actionlink like this:
#Html.ActionLink("Delete", "Your-Action", new { id = item.id },
new { onclick="return confirm('Are you sure?');"})
Don't get confused between route values and the html attributes.
<a onclick="MyFunc()">blabla..</a>
There is nothing more in #Html.ActionLink that you could utilize in this case.
And razor is evel by itself, drop it from where you can.
#Html.ActionLink("Edit","ActionName",new{id=item.id},new{onclick="functionname();"})
This is a bit of an old post, but there is actually a way to do an onclick operator that calls a function instead of going anywhere in ASP.NET
helper.ActionLink("Choose", null, null, null,
new {#onclick = "Locations.Choose(" + location.Id + ")", #href="#"})
If you specify empty quotes or the like in the controller/action, it'll likely add a link to what you listed. You can do that, and do a return false in the onclick. You can read more about that at:
What's the effect of adding 'return false' to a click event listener?
If you're doing this onclick in an cshtml file, it'd be a bit cleaner to just specify the link yourself (a href...) instead of having the ActionLink handle it. If you're doing an HtmlHelper, like my example above is coming from, then I'd argue that calling ActionLink is an okay solution, or potentially better, is to use tagbuilder instead.
This is the only one that worked for me in .cshtml file:
#Html.ActionLink(
"Name",
"Action",
"Controller",
routeValues: null,
htmlAttributes:new Dictionary<string, object> {{ "onclick", "alert('Test');" }})
I hope this helps.
Related
I am new in MVC environment and I just started upgrading a website.
Problem
Object reference not set to an instance of an object.
Explanation
I have javascript function for a button in the view and I am trying to get a property value CurrentPageNo from the associated model as shown below.
$('#pPrevious').on('click', function (event) {
event.preventDefault();
this.blur();
if (ShowBusy()) {
getPageIndexChanging(#Model.CurrentPageNo-1);
}
});
I am referring to the model as below:
#code
ViewBag.Title = "Home"
End Code
#ModelType HomeModel
#Using (Html.BeginForm("Index", "Home", FormMethod.Post, New With {.id = "indexForm", .name = "indexForm"}))
Try
#Html.AntiForgeryToken()
etc...
When I put a breakpoint in the model it doesn't work.
What Am I doing wrong in this situation ?
It is difficult to Get c# model data in your javascript code.
Simply you can add the value in a text box that is hidden and get value with getElementById in your javascript code.
I'm trying to use javascript variables inside laravel blade.
But I'm getting this error.
What should I do for using this ?
var activeTab = $("ul#tablist li.active");
var floor = {!! \App\Floor::find(activeTab.attr('id')) !!}
Use of undefined constant activeTab - assumed 'activeTab'
Ok, so you can have another route like this:
Route::post('/getFloorById', [
'uses' => 'YourController#getFloorById',
'as' => 'getFloorById'
]);
Then, in you controller you have the method:
private function getFloorById($segments)
{
$floorId = $segments[1];
return \App\Floor::find($floorId);
}
And last, you need your javascript code:
var floor = $.post('/getFloorById', {"id": activeTab.attr('id')});
This is the ajax method. Keep in mind that you might need to use echo instead of a return. And you might need to wrap your code into json_encode(\App\Floor::find($floorId)) like this, but for the most part this should get the job done.
You might want to call the post from an onclick event that way you get the new object every time the tab changes.
Unfortunately blade is just a framework to output php. You don't need to do that, and you won't be able to anyways. That would be a big security issue.
If you really need that floor use what #Rohan suggested, javascript directly:
var floor = activeTab.attr('id');
I have a javascript function and when it is called I want to insert a partial into a div. All is working fine, but, when I want to pass some javascript into Html.Partial ViewDataDictionary, it isn't passing the rendered javascript.
<script>
function addExperience() {
#{var uid = #MvcHtmlString.Create("new Date().getTime()");}
console.info(#uid); //output ok !
var partialView = #(Html.Raw(JsonConvert.SerializeObject(Html.Partial("~/Views/Dashboard/_editUserExperience.cshtml", Model, new ViewDataDictionary { { "id", uid } }).ToString().Trim('"'))))
$("#newExperienceSection").append(partialView); //it renders "new Date().getTime(), not the number
}
</script>
Thank you !
If you call Jsonconvert.SerializeObject with a string (Html.Partial returns a string), it returns a string.
So you statement
var partialView = ... will be rendered as
var partialView = "the contents of the partial view";
That's why, when you do this:
$("#newExperienceSection").append(partialView);
it actually displays the javascript as text.
If you want to get a partial view to execute javascript, you can return javascript inside script tags, and as soon as you add that to the DOM it gets executed, for example if you set your _editUserExperience.cshtml as this:
<script>
alert('this gets executed as soon as you do add this to the DOM with the jQuery append command');
</script>
When you execute $("#newExperienceSection").append(partialView); you'll see the alert.
An easier way to insert a partial view is to take advantage of $.ajax, for example, in addExperience:
$.get('#Url.Action("ActionMethodThatReturnsPartial", "YourController")').done(function(theHtmlReturned) {
$("#newExperienceSection").html(theHtmlReturned);
});
($.get is just shorthand for $.ajax using a get request)
Source: http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.get/
http://api.jquery.com/category/deferred-object/
I swear this used to work. I am trying to do breadcrumbs. I have a JS function in the global namespace called "breadcrumb". It accepts a string as its only parameter:
function breadcrumb(attr) {
hash = { type: "POST", url: "brands/get_attributes", data: $("#attributeform").serialize() };
$.ajax(hash);
return false;
}
I have my breadcrumb link on the HTML page defined as follows:
<%= value %>
Fine so far. But when I click the breadcrumb link, I get this in the URL:
javascript:breadcrumb('Whirlpool');
And a blank page with the word "false", which is what the function returns. My question is, why is it actually navigating to the javascript function itself? Why is the Ajax result not being rendered?
Use onclick rather than href. Also, the OCD in me suggests the following syntax change:
var hash = { //use braces to define an object
type: "POST",
url: "brands/get_attributes",
data: $("#attributeform").serialize()
};
Change href to onclick:
<%= value %>
It is because your <a> tag's href doesn't contain a void(0); statement at the end, so the value of your breadcrumb function is returned to the browser.
Try changing:
href="javascript:breadcrumb(\'<%= brand_attribute.attributename %>\');"
to:
href="javascript:breadcrumb(\'<%= brand_attribute.attributename %>\');void(0);"
edit: I would also agree with jakubka's answer, it would be better practice to keep javascript calls in the onclick attributes of your links as opposed to the href.
So,
href="#" onclick="breadcrumb(\'<%= brand_attribute.attributename %>\');"
I'm trying to trigger a postback from java-script and also pass event args. I'm able to trigger the postback **but not able to pass event args.
The below function does not work. It does not like the args parameter in ClientScript.GetPostBackEventReference.
<script type="text/javascript">
function TriggerServerSideClick(args) {
//btnDummy is a asp.net server-side button control
<%=ClientScript.GetPostBackEventReference(btnDummy, args , true)%>
//tried this -> <%= 'ClientScript.GetPostBackEventReference
// (btnDummy,' + args + ', true)' %> ,
// but i guess i am definitely missing something.
}
</script>
What am I missing here ?
I know that the following works
__doPostBack('btnDummy', args);
but want to stay away from __doPostBack as that could change eventually and try the ClientScript.GetPostBackEventReference instead.
Thanks for your time.
#Brian: Thanks a lot for following up. I tried your placeholder approach but I am getting a javascript error. (Message: Expected ';')
Here is the viewsource snippet:
var postbackUrl = '__doPostBack('ctl00$MainContent$btnDummy','{0}')';
function TriggerServerSideClick(args) {
var url = String.format(postbackUrl, args);
eval(url);
}
Try this:
var postbackUrl = '<%=ClientScript.GetPostBackEventReference(btnDummy, "{0}", true)%>';
function TriggerServerSideClick(args) {
var url = String.format(postbackUrl, args);
eval(url);
}
Put a placeholder where the argument should be, then use a client-side method to replace the placeholder (client-side String.format method) and use that to postback.
HTH.
The answer from Brian Mains sent me in the right direction when I was working on this issue just now. The only difference being, that I didn't use the client-side string.Format - I used the mainstream JavaScript string.replace:
//js
args = someComplicatedDynamicStuff();
myPostback = <%= Page.ClientScript.GetPostBackEventReference(this, "args")
.Replace("'", "\\'") %>; // server-side replace to
// inject string delimiters
eval(myPostback.replace('args',args));