Execute Javascript inside a partial view in ASP.NET MVC - asp.net-mvc

I use this JavaScript code inside the head tag in order to populate the divs with a browse button so that users can upload images (swfupload).
<head>
...
<script type="text/javascript">
var swfu = function() {
return new SWFUpload({
// Backend Settings
// settings go here...
// Too long to display here
// Debug Settings
debug: false
});
}
window.onload = swfu;
</script>
</head>
....
<div id="swfu_container" style="margin: 0px 10px;">
<div>
<span id="spanButtonPlaceholder"></span>
</div>
<div id="divFileProgressContainer" style="height: 75px;"></div>
<div id="thumbnails"></div>
</div>
This works well, but the problem is when I try to put this code inside of a partial view. So far, I haven't be able to get this to work.
Is there anyone more experienced to the rescue?
Thank you

You can put your function like this:
<%= Ajax.ActionLink("YourAction",new AjaxOptions{ OnSuccess="swfu", UpdateTargetId = "spanButtonPlaceholder" }) %>
so your swfu function will be called if your update is successfull

The point of window.onload is to execute the given function once the page has finished... loading. That said, you should consider moving the onload to the bottom of the body. And I'm not the worlds biggest fan of keeping scripts in the head. :)

Partial views are rendered with Microsoft Ajax which does not evaluate JavaScript code. I would suggest looking at not using partial views in this case or look at other view engines like Spark....or put all required javascript in your parent view which kinda makes your code a bit sloppy

Related

Asp.net MVC button does not show

I place a button in a div tag, and when I run it, I only see the div container
<div style= "border-style:solid;border-width:1px; padding:5px; background-color:#ffffcc">
<asp:button ID = "refresh" runat ="server" OnClientClick="reloadPage()">
<script type="text/javascript">
function reloadPage(){
window.location.reload()
}
</script>
</asp:button>
</div>
the refresh button is nowhere can be found. Are there anything wrong with my code? I am new to MVC, please give me suggestions.
Why are you using asp controls in an MVC project -> use an HTML element.
Use a Form
<div>
#using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
<button type="submit">Submit</button>
}
</div>
Use a Button
<div>
<button onclick="DoSomeJavascript" >Submit</button>
</div>
MVC uses Controllers (Code Behind) and Views (Html) to create pages. To send data to or from a page you need to use View Models.
Maybe have a look at this handy guide: http://www.asp.net/mvc/overview/getting-started/introduction/getting-started
Your question states that you are new to MVC, yet you are trying to define a button from classic ASP.NET, which will not be processed by the Razor view engine used by MVC. Since you are just reloading the page you can do this with regular HTML buttons and Javascript. I'm not reloading the page here in this snippet, but that's irrelevant.
<div style="border-style:solid; border-width:1px; padding: 5px; background-color:#ffffcc">
<button id="refresh" onclick="reloadPage()">
Refresh Page
<script type="text/javascript">
function reloadPage() {
console.log("Reloaded")
//Reload page here
}
</script>
</button>
</div>
If you run this and click you should see the log message in your Javascript console.

Jquery date picker in Meteor.js

I am trying to use jquery datepicker in my project, but I want to show it when the user in editing mode. When I use it without if statement, it works perfect, but when I put in if statement, it does not render. How can I solve this?
This is the part of my template
{{#if editing_duedate}}
<input class="datepicker" name="date">
{{else}}
<div class="row text-center">
<div class="eventduedate">
{{duedate}}
</div>
</div>
{{/if}}
This where I render datepicker
Template.assignmenttodositem.rendered = function() {
$('.datepicker').datepicker();
};
This is my template events
Template.assignmenttodositem.events({
......
'dblclick .eventduedate':function(evt,tmpl){
evt.preventDefault();
Session.set('editingduedate', this._id);
}
..........
This is where I check if statement
Template.assignmenttodositem.editing_duedate = function () {
return Session.equals('editingduedate', this._id);
};
Rendered is executed only once, when template is rendered.
In that time else part is not put to HTML so .datepicker cannot be found.
You need to check whether editinduedate variable is updated and then create datePicker component.
Template.assignmenttodositem.rendered = function() {
var self = this;
this.autorun(function(){
if(Session.equals("editingduedate", self.data._id )){
$('.datepicker').datepicker();
}
})
};
HTML
<template name="assignmenttodositem">
{{#if editing_duedate}}
{{> datepicker}}
{{else}}
...
{{/if}}
</template>
<template name="datepicker">
<input class="datepicker" name="date">
</template>
JS
Template.datepicker.rendered=function(){
this.$('.datepicker').datepicker();
};
The rendered callback is executed only once when your template instance is inserted in the DOM : triggering the datepicker initialization in the enclosing template containing the #if statement is not going to work because when it is executed, we are in the else state so the input is not there yet.
To solve this problem simply, just move the datepicker in its own template (this has always been considered a good design pattern in programming anyway, whenever you can, decompose your main task in smaller easier solvable tasks), this way its rendered callback will get executed at appropriate time.
Put the datepicker in it's own template. Then initialize the datepicker in template.datepicker.rendered . If you forget the 'this' context, it will not work. Make sure your template.datepicker.rendered includes the following
this.$('#datepicker').datepicker();
where #datepiker refers to id='datepicker' of the datepicker in html.

Partial View Based Web Site - Asp.Net MVC 4

I'm working on a project and i have to deal with some unusual design for me. My goal is to work with 2 different simultaneous work area. Left one should change its value between 2 different partial view. The second one (mid and right area), should change its views independently from the left one.
So, at the end, i end up with 2 different divs, left and right one and Jqueryiu Tab plugin... after clicking one of the tabs i load the partial view inside it.
<div id="conteudo">
<div class="container-abas-laterais">
<div id="abas-laterais" style="width: 100%; height: 100%">
<ul>
<li>Pendências</li>
<li>Requerimentos</li>
</ul>
</div>
</div>
<div class="container-abas">
<div id="abas">
<ul>
<li>Chamados</li>
<li>Cadastros</li>
<li>Pesquisa</li>
<li>Configuração</li>
</ul>
<div class="container-abas-conteudo">
<div id="aba-1">
<p>Conteúdo da aba um.</p>
</div>
<div id="aba-2">
<p>Conteúdo da aba dois.</p>
</div>
<div id="aba-3">
<p>Conteúdo da aba três.</p>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () { $("#abas").tabs(); });
$(function () { $("#abas-laterais").tabs(); });
</script>
Well, the partial views loaded directly from the tabs clicks worked really well, just as i wanted... the problem is the ones that those initial views should also call... i need to keep all the views and functions inside those divs... it should act like an iFrame.. wah, sometimes, what i do in left one should take place in right one...
So i wanted to know some tips or ways to achieve this kind of behaviour in asp.net mvc. Please, if my idea is confuse or not well detailed, just let me know...
Thanks for the help.
If I am interpreting you correctly: that you want to load up the second set of tabs based on those links in the first set? If so, it would be something like this for your links:
#Ajax.ActionLink("Requerimentos", "Requerimento", "AcessoRapido", null, new AjaxOptions{ UpdateTargetId = "aba-1", OnSuccess = "changeTabs(1)" }, null)
And the action that link invokes will need to return a PartialView as your action result. Then on a successful return, you will see that it's calling a function on success where you can change the tab to the one you want.
function changeTabs(index){
$("#abas").tabs("select", index);
}
If all the assumptions are correct, don't forget that you will need to include unobtrusive ajax in your page and also the correct key in your web.config:
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
Forgive me if I have misinterpreted your question. I hope this helps.

Why is my dynamically-added content not rendering with jQuery Mobile?

I'm using jQuery Mobile + Backbone + RequireJS. After successful login I do the following:
require(['app/view/main'], function(MainView) {
var mainView = new MainView();
$('body').html(mainView.render().el);
});
and render() looks like
render: function() {
this.$el.html(this.template);
return this;
}
Upon doing so, my page is blank. Inspecting the body, I do see the following HTML inside the body:
<div data-role="page" id="main">
<div data-role="header" data-position="inline">
<h1>Accounts</h1>
</div>
<div data-role="content">
hello
</div>
</div>
I've also tried doing this inside render():
this.$el.html(this.template).trigger('create');
as well as
this.$el.html(this.template).page();
but the page is still blank. Any ideas why?
If I simply put the HTML inside the body and load the page, it displays fine, like a normal jQuery Mobile app would.
Are you waiting until after pageinit to trigger / create your page?
$(document).bind('pageinit', function() {
// trigger
});
Also, jQM may be interpreting your markup as a single page template and then by injecting a data-role='page' element, you are marking up a multiple page document (with only a single page). Try leaving the <div data-role='page'> element in your default markup and then dynamically add the header, content and footer. jQM should then correctly interprete the markup and enhance it accordingly.

How to use a template for all jQuery Mobile pages?

Behold: a footer template:
<!-- Templates -->
<script type="text/template" id="templateFooter">
<div data-role="navbar">
<ul>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</script>
In every mobile page I have:
<div data-role="footer" data-position="fixed">footer</div>
The way I'm currently loading the template is:
$(function() {
$('div[data-role=footer]').html($('#templateFooter').html());
$.mobile.activePage.trigger('create');
});
This works, but I don't really like using $(function(), but I need to load it if any page shows, so pageinit or pageshow does not help. I'll be using knockout.js going forward, if that is of any help.
Is there a better way to do this?
function getTemplateFooter() {
//return footer text here
}
$("div:jqmData(role='page')").live("pagebeforecreate",function() {
// get the footer of the page
// if footer doesn't exist on page, insert it where you want it... in this case after role="content"?
var $content =$(this).page().find('div:jqmData(role="content")');
$content.after(getTemplateFooter());
}
there is also a pageshow event, that one fires even if the user navigates to the page, through a back button press etc... it bubbles up to the page div
I use it for pages where lots of dynamic data could change between subsequent visits, or even when the user just presses back

Resources