Asp.net MVC button does not show - asp.net-mvc

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.

Related

Vue + Asp.net rendering issue

I have a new asp.net mvc project (not .net core) and I am trying to incorporate Vue js into the project. I have everything working in a sample project using Webpack+Vue+Asp.Net Mvc, which was created following this article https://medium.com/corebuild-software/vue-js-and-net-mvc-b5cede228626.
The app works great, except for the split second before Vue renders. There is noticable flashing/popping of the Vue templated code before its rendered to html. Below is a gif of me refreshing the page and users are able to see the template before Vue renders it into html.
I know why this is happening, but I do not know any ways around it. Would Server Side Rendering fix this? Can SSR be done in a non .net core project?
Unfortunately, switching to asp.net core is not an option. The project will be using Umbraco 7, which cannot run on asp.net core (https://our.umbraco.com/forum/using-umbraco-and-getting-started/93640-net-core).
Below are my files
Index.cshtml
#{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p>Learn more »</p>
</div>
<div id="app" controller-data="{ name: 'James' }">
<h3>Test</h3>
{{ vueMessage }}
{{ controllerData }}
<first-component v-bind:time="new Date()" data="#Model"></first-component>
<button v-on:click="test">Test</button>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<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>
<p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div>
#Scripts.Render("~/Scripts/bundle/home.js")
index.js (gets compiled to Scripts/bundle/home.js by webpack)
import Vue from 'vue';
import FirstComponent from './sub-components/first-component.vue'
new Vue({
el: '#app',
components: {
FirstComponent
},
props: {
controllerData: Object
},
methods: {
test: function () {
console.log(this);
}
},
data: function () {
return {
vueMessage: 'Message from Vue'
};
}
})
first-component.vue
<template>
<div class="time">
{{ time }}
{{ data }}
</div>
</template>
<script>
export default {
props: {
time: {
type: Object,
required: true,
},
data: Object
}
}
</script>
<style>
.time {
color: #F44336;
}
</style>
Make use of the v-cloak attribute.
<div id="app" v-cloak>
...
</div>
The attribute is automatically removed by vue when the framework has finished mounting.
The v-cloack attribute does not show or hide your elements - it is basically a marker that indicates if mounting is finished. You write a css selector to target v-cloack to hide the elements or show a loading indicatior.
<style>
[v-cloak] > * { display:none }
[v-cloak]::before { content: "Please wait…" }
</style>
Switching to .net core or any other server side technology would not help.
The issue is because the html is rendered by the browser as it downloads & before all the script resources have downloaded/parsed/run & rendered the html from the Vue component.
When dealing with mixed rendering (partially server side & partially client side) your best option is to hide the template by default & "show" it once the vue component is setup & ready.
For example in your server side view, hide <div id="app"> either with an attribute, style or class.
<style>#app.loading {display:none;}</style>
<div id="app" v-bind:class="{ loading: !isloaded }">
Then in your vue component mounted method set isLoaded to true. This is just one of many ways to hide the component before it's ready.

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.

Form checkboxes not being displayed correctly second time shown

I have a weird problem with a simple form with checkboxes..
The first time it's shown it looks fine.. But then after navigating back to the previous page and be to it again - the ui is not updates resulting in plain checkboxes without jQuery mobile style..
I've Googled like crazy and found a couple of hints like .fieldcontain(); but it's doesn't work =(
The data is being retrieved through knockout bindings..
Any good ideas?
Here's the code...
<div id="searchCitiesPage" data-role="page" data-theme="a" class="page searchCities">
<header data-role="header" data-theme="b">
</header>
<div data-role="content" class="content" data-theme="a">
<script id="countyListTemplate" type="x-jquery-tmpl">
<form id="fieldform" action="form.php" method="post">
<fieldset id="fieldsetgroup" data-role="controlgroup">
{{each BoligPortal.AdSearch.postalcodesInSelectedCounty}}
<input type="checkbox" name="checkbox-${zipcode}-${timestamp}" id="checkbox-${zipcode}-${timestamp}" class="zipcodecheckbox"/>
<label for="checkbox-${zipcode}-${timestamp}">${zipcode} ${city}</label>
{{/each}}
</fieldset>
</form>
</script>
<div data-bind="template: 'countyListTemplate'"></div>
<div class="submit">
Næste
</div>
</div>
I was having a problem like this too, but in my case, the checkboxes were being redrawn dynamically before loading the page. I tried refreshing:
$("input[type='checkbox']").checkboxradio("refresh");
But it gave me an error stating that checkboxradio hadn't been initialized. However, when I tried this instead:
$("input[type='checkbox']").checkboxradio();
It made the checkboxes appear correctly every time. I'm still fumbling in the dark with JQuery Mobile and can't say exactly what happens where and why (I think I'm initializing the checkboxes?), but I thought I would share for the next time someone like me googles their way to this thread.
You can add some javascript to re-initialize the jQuery Mobile markup for your checkbox on each page load. Something like this:
<script type="text/javascript">
$(function() {
$('[data-role=page]').live('pageshow',function(){
$('#fieldform').find('input').checkboxradio();
});
});
</script>
I would suspect this code
{{each BoligPortal.AdSearch.postalcodesInSelectedCounty}}
<input type="checkbox" name="checkbox-${zipcode}-${timestamp}" id="checkbox-${zipcode}-${timestamp}" class="zipcodecheckbox"/>
<label for="checkbox-${zipcode}-${timestamp}">${zipcode} ${city}</label>
{{/each}}
is being called again when you transition back to the page. I would suggest pulling the infomation/tags/etc.. before the page displays (on the first load) and display it statically. So when transitioning back it shows the same data.
of you could use one of the live events and restyle it before the page shows, example:
$('.zipcodecheckbox').live('pagebeforeshow',function(event, ui){
$("input[type='checkbox']").checkboxradio("refresh");
// or
$(".zipcodecheckbox").checkboxradio("refresh");
});

How to use a jQuery UI Modal Form from ASP.Net MVC list page

I am tryng to use this: http://jqueryui.com/demos/dialog/#modal-form
I have:
<script type="text/javascript">
$(document).ready(function() {
$("#dialog").dialog();
$("#dialog").dialog('close');
$('.myPop').click(function() {
$("#dialog").dialog('open');
});
});
Which allows me to pop-up on the click of '.myPop' which is just a temp input button in my list which is working:
<button type="button" class="myPop"></button>
My question is - what is the best way to use this pop-up to go to the Edit method of my controller, populate controls and then be able to save back to the model and refresh the list page?
I want to keep with best practice in ASP.Net MVC please.
Am I beetr maybe using this? http://dev.iceburg.net/jquery/jqModal/
Thanks
There's obviously a bunch of ways to do that, but here's how I would solve it. Perform an ajax call before loading the dialog to populate the dialog's contents, show the dialog, than on save close the dialog and refresh the grid. Those are the basics, there's some helper code below. I find it a good practice to return a json result from the save action to determine if the saved was successful, and if not an error message that indicates why it failed to display to the user.
<div id="dialog" title="Basic dialog">
<!-- loaded from ajax call -->
<form id="exampleForm">
<input blah>
<input type="button" onclick="Save()" />
</form>
</div>
<script>
$(function() {
$('.myPop').click(function() {
$.get("editController/loadContents", function(data){
$("#dialog").html(data);
});
$("#dialog").dialog('open');
});
});
function Save(){
$.post("/editController/Edit", $("#exampleForm").serialize(),
function(data){
$("#dialog").dialog('close');
//update grid with ajax call
});
}
</script>

Execute Javascript inside a partial view in 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

Resources