Caching in asp.net MVC4 - asp.net-mvc

I'm trying to update my web page's time every 3 seconds. this is how how i'm trying to do it:
[OutputCache(Duration = 3)]
public ActionResult Index()
{
ViewBag.Message = "Time : " + DateTime.Now;
return View();
}
but it does't refresh the page. Can someone please give me an idea how to solve this. thank you in advance!

You can Achieve it by using java script in asp form.
<p id="demo"></p>
<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>

You also may use the meta tag for refreshing the page if it's ok to hit the server as below,
<meta http-equiv="refresh" content="3;">

Related

Retrieve object from URL in mvc

This is for a school project, and I don't really understand exactly what I'm supposed to do, so I'll explain what the teacher told me and what I did so far, hope you guys can help.
To examine the success of a program, the teacher wants to manually add a number to the url of the page.
I need to take that number, extract it from the url, then implant it in a method so that it will decrypt a message with the same ID number (I have no idea how he intends to do it or activate said method).
Here is what I wrote:
In the DataModel:
public static void GetMessage (int? MesNum, out string MesSuc)
{
SqlConnection cnctn = new SqlConnection(cnctnstrng);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cnctn;
cmd.CommandText = "GetMessage";
cmd.Parameters.Add("#LineNum", SqlDbType.Int);
SqlDataReader rd;
try
{
cnctn.Open();
cmd.Parameters["#LineNum"].Value = MesNum;
rd = cmd.ExecuteReader();
byte[] Message = (byte[])rd["MessageText"];
if (Message != null)
{
MesSuc = chat.Models.DomainModels.Security.DecryptStringFromBytes(Message);
}
else
{
MesSuc = "Unable to decrypt Message";
}
}
catch
{
MesSuc = "Unable to decrypt Message";
}
finally
{
cnctn.Close();
}
}
In the Controller:
public ActionResult singlmsgdecrptn()
{
string MesSuc;
chat.Models.DataModels.userdbmanip.GetMessage(*?*, out MesSuc);
return View(MesSuc);
}
The ? is where the number is supposed to come in.
In the View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>singlmsgdecrptn</title>
</head>
<body>
<div>
#ViewBag.MesSuc
</div>
</body>
</html>
The default routing for MVC takes and ID optional parameter. Check the RouteConfig.cs in the App_Start folder.
So you should just be able to add it as a parameter to your controllers action result.
public ActionResult singlmsgdecrptn(int? id)
{
string MesSuc;
chat.Models.DataModels.userdbmanip.GetMessage(id, out MesSuc);
return View(MesSuc);
}
Also, not sure why you're using a nullable int here, but I followed suit. Hope this helps, good luck.

ASP.NET MVC - Execute controller action without redirecting

I am trying to execute an action on a controller without redirecting to the associated view for that action. For a good example of what I am trying to achieve take a look at the music.xbox.com website. When you add a song to a selected playlist from a popup menu - the page just shows a notification without any redirect or refresh. how is this possible?
What I have is the following:
I have a _playlistPopupMenu partial view that renders the list of playlists as follows:
_PlaylistPopupMenu
#model List<OneMusic.Models.GetPlaylists_Result>
#if (Model.Count > 0)
{
<li style="height:2px" class="divider"></li>
foreach (var item in Model)
{
<li style="height:30px">#Html.DisplayFor(p => item.Name)
#Html.ActionLink(item.Name, "AddSong", "Playlist", new { playlistId = #item.PlaylistId, songId = 1 }, "")
</li>
}
}
The PlaylistController AddSong action is as follows:
public PartialViewResult AddSong(int? playlistId, int? songId)
{
if (ModelState.IsValid)
{
db.AddSongToPlaylist(playlistId, songId);
db.SaveChanges();
return PartialView("_AddToPlaylist", "");
}
return PartialView("_AddToPlaylist", "");
}
I am struggling with what to put in the _AddToPlaylist partial view which I think I need to be able to display a notification of some kind (Possiblly using PNotify add in for Bootstrap). MVC wants to always redirect to ../Playlist/AddSong?playlistId=1&songId=1
Any ideas on how to complete this last part of the problem would be great.
If you don't want "full page reloads" then you need to approach the problem slightly differently, using javascript to alter the page dynamically. A library such as JQuery might make manipulating the DOM a little easier.
Display the popup dynamically using javascript.
When the user hits OK/Submit on the popup, post the data back to the server using javascript, and have the controller you are posting to return some HTML.
Append the returned HTML block (partial view) to an existing div containing playlist tracks.
The most difficult part of this is the asynchronous post. Help with updating a div without reloading the whole page can be found in this question.
EDIT - Example
If you have a controller action (accepting POSTs) with the URL myapp.com/PlayList/AddSong/, then you'd set up JQuery to post to this URL. You'd also set up the data property with any form data which you'd like to post, in your case you'd add playistId and songId to the data property.
You'd then use the result of the AJAX query (HTML) and append it to the existing playlist HTML on the page. So assuming that you want to append the partial view's HTML to a div with ID playlistDiv, and assuming that your partial view returns HTML which is valid when appended to the existing playlist, then your javascript will look something like this:
var data = { playlistId: 1, songId: 1 };
$.ajax({
type: "POST",
url: 'http://myapp.com/PlayList/AddSong/',
data: data,
success: function(resultData) {
// take the result data and update the div
$("#playlistDiv").append(resultData.html)
},
dataType: dataType
});
Disclaimer: I can't guarantee that this code will work 100% (unless I write the program myself). There may be differences in the version of JQuery that you use, etc, but with a little tweaking it should achieve the desired result.
using System.Web.Mvc;
using System.Web.Mvc.Html;
public ActionResult Index()
{
HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
helper.RenderAction("Index2");
return View();
}
public ActionResult Index2(/*your arg*/)
{
//your code
return new EmptyResult();
}
in your controller you must add bottom code:
public ActionResult Index(string msg)
{
if (Request.Url.ToString().Contains("yourNewExampleUrlWithOutRedirect.com"))
{
string html = "";
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Encoding = Encoding.UTF8;
html = client.DownloadString("https://NewExampleUrl.com/first/index?id=1");
}
Response.Write(html);
}
...
}
your view must be empty so you add bottom code
#{
ViewBag.Title = "sample title";
if (Request.Url.ToString().Contains("yourNewExampleUrlWithOutRedirect.com"))
{
Layout = null;
}else
{
Layout ="~/Views/Shared/_Layout.cshtml"
}
}
#if (Request.Url.ToString().Contains("yourNewExampleUrlWithOutRedirect.com")==false)
{
before view like :
<div>hello world</div>
}

Struts2 autogenerated dropdownlist doesn't refresh new items on the second select

I have try to implement a form with two select on my form, with doubleselect tag of struts 2, where the content of the second select is conditioned from the first. So surfing the net, i have found the post : http://www.mkyong.com/struts2/struts-2-sdoubleselect-example/, i have try the example suggested by the blogger, but when i choose an element from the first select, the second select did not change it's value.
So, i have debbuged it with firebug on mozilla 17.01 and the javascript autogenerated with the jsp tag doubleselect seems good, cause i have any error into the console. Debugging the code autogenerated with the struts 2 tag, s:doubleselect, i have saw that option element are removed well, but maybe the second select is not refreshed. So for example on the example, when the page is in the firse select i have .net language and in the second .sharp and .vnet, when in the first i choose java, onChange, onDebugg the function that permits to change items to the second select is trigger, the old options are deleted , and the new options are created ad inserted in the the second, but the content of the second select did not change on the page.
So on the link, i have used used the last exampe, programming language:
jsp form
<form:main action="DoubleSelectAction" id="channelerForm">
<s:doubleselect label="Language (Java List) "
id= "Test1"
name="language1"
list="languageMap.keySet()"
doubleId="secondoItem"
doubleName="language2"
doubleList="languageMap.get(top)" />
</form:main>
Define the Action:
public class DoubleSelectAction extends ActionSupport{
private String language1;
private String language2;
Map languageMap;
public String getLanguage1() {
return language1;
}
public void setLanguage1(String language1) {
this.language1 = language1;
}
public String getLanguage2() {
return language2;
}
public void setLanguage2(String language2) {
this.language2 = language2;
}
public Map getLanguageMap() {
return languageMap;
}
public void setLanguageMap(Map languageMap) {
this.languageMap = languageMap;
}
public DoubleSelectAction(){
languageMap =new HashMap();
languageMap.put("Java",
new ArrayList<String>(Arrays.asList("Spring", "Hibernate", "Struts 2")));
languageMap.put(".Net", new ArrayList<String>(Arrays.asList("VB.Net", "C#")));
languageMap.put("JavaScript", new ArrayList<String>(Arrays.asList("jQuery")));
}
public String execute() {
return SUCCESS;
}
public String display() {
return NONE;
}}
So i would like to know if someone has had the same problem,
thanx for yours time.
I think you are trying to wrapping tag inside wrong form tag
I mean to say you might be declared this tagLib (<%# taglib prefix="s" uri="/struts-tags"%>)
you must use the same form rather using form:main tag
I just giving the sample jsp which is successfully rendering .
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="DoubleSelectAction" id="channelerForm">
<s:doubleselect label="Language (Java List) "
id= "Test1"
name="language1"
list="languageMap.keySet()"
doubleId="secondoItem"
doubleName="language2"
doubleList="languageMap.get(top)" />
</s:form>
</body>
</html>
Hope it helps

how to use mvc4 model value in knockout viewmodel js

I am using Knockout with ASP.NET MVC here is my View which is populated by MVC controller
HTML
<html>
<input type="text" data-bind="value:Name" />
<script src="/Scripts/ViewModel.js"></script>
</html>
Controller
public actionresult xyz(){
var myModel = new FiestModel();
myModel.Name = "James";
return view(myModel);
}
ViewModel.Js
function mymode(){
var self = this ;
self.Name = ko.observable('#Model.Name');
}
after doing all of this when my page render my input doesn't have the specified value James .
Update
I tell you guys about the whole scenario , in my application a user click on signup with facebook button and facebook return user back to my xyz action method , now i want to show the username in xyz view . So how can i do this with api because #Anders said me to do this by Web APi .
Thanks in advance .
You shouldnt mix server side MVC and client side MVVM.
Move the model population to a WebAPI controller method.
Load the data using jQuery.getJSON or other framework for Ajax
You can also use ko.mapping to map the server data into ViewModels
edit: code in ViewModel.js have to be moved to the cshtml file if oyu want to use
#Mode.Name, but please dont do it.
Update
Something along the lines
[HttpGet]
public FiestModel xyz() {
return new FiestModel("James");
}
With mapping plugin something like
ViewModel = function(data) {
ko.mapping.fromJS(data, {}, this);
};
$.getJSON("api/myController/xyz", null, function(data) {
ko.applyBindings(new ViewModel(data));
});
Try with something like on JS:
function myModel(){
var data = #(Html.Raw(Json.Encode(Model)));
this.Name = ko.observable(data.Name);
}
Then you bind your view model:
ko.applyBindings(new myModel());

ASP.NET MVC refresh header issue

I want to call an action method (DownloadPictures) after i redirect to a different page, so i use the refresh header
UrlHelper url = new UrlHelper(Request.RequestContext);
Response.AddHeader("REFRESH" , "1;URL=" + url.Action("DownloadPictures" , "Cart" , new { isFree = true }));
return Redirect(returnUrl != null ? returnUrl : url.Action("Index", "Home"));
And my Download Pictures method looks like this with a breakpoint set on the first line, but this method never gets called
public ActionResult DownloadPictures ( bool? isFree ) {
Cart cart = (Cart)HttpContext.Session["_cart"];
....
//The Download Picture Method returns a File (a zip file)
}
Any help would be appreciated. Thanks
Most browsers ignore the refresh header
Use another method like javascript etc
e.g.
<html>
<head>
<script type="text/javascript">
function delayRedirect()
{
window.location = "/DownloadPictures";
}
</script>
</head>
<body onLoad="setTimeout('delayRedirect()', 1000)">
...
</body>
</html>

Resources