ASP.NET MVC refresh header issue - asp.net-mvc

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>

Related

Caching in asp.net MVC4

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;">

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());

Not receiving JSONP callback

I am following the sample code/tutorial for ASP.NET MVC and JSONP blog post: http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
I have taken the code sample and have modified it for my own consumption.
When I hit the page, it fires off my controller's action but the $.getJSON(call, function (rsp).. is not firing at all.
Controller action
[JsonpFilter]
public JsonpResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return new JsonpResult
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
HTML Page
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var url = "http://localhost/MySite.ContentDelivery/MyController/GetMyObjects/?";
function getObjects() {
//
// build the URL
//
debugger;
var call = url + "id=48&jsoncallback=?";
//
// make the ajax call
//
$.getJSON(call, function (rsp) {
debugger;
alert(rsp);
if (rsp.stat != "ok") {
//
// something went wrong!
//
$("#myDiv").append(
"<label style=\"background-color:red;color:white;padding: 25px;\">Whoops! It didn't work!" +
" This is embarrassing! Here's what the system had to " +
" say about this - " + rsp.message + "</label>");
}
else {
//
// build the html
//
var html = "";
$.each(rsp.list.myObject, function () {
var obj = this;
html += "<span" + obj.Name + "</span> <br />";
});
//
// append this to the div
//
$("#myDiv").append(html);
}
});
}
//
// get the offers
//
$(document).ready(function() {
alert('go..');
$(getOobjects);
});
</script>
<div id="myDiv"></div>
</body>
</html>
tl;dr why is my getJson() not firing while my getObjects() fires and executes the MVC controller action.
Replace:
var call = url + "id=48&jsoncallback=?";
with:
var call = url + "id=48&callback=?";
The custom JsonpResult you are using relies on a query string parameter called callback and not jsoncallback:
Callback = context.HttpContext.Request.QueryString["callback"];
Also you have decorated your controller action with a [JsonpFilter] attribute and returning a JsonpResult. As explained in the article you must have read you should choose one:
[JsonpFilter]
public ActionResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return Json(list, JsonRequestBehavior.AllowGet);
}
or the other:
public ActionResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return new JsonpResult
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
but do not mix the two.

ASP.NET MVC two user control

I have two user controls on the page and one of the user control has this text aread.
which is used to add a note and but when they click add note button the page reloads.
I do not want the page to reload ,i was looking for an example which this is done without
postback.
Thanks
i tired doing this using JSON , but it throws the following error
The HTTP verb POST used to access path '/Documents/TestNote/Documents/AddNote' is not allowed.
<script type="text/javascript">
$(document).ready(function() {
$("#btnAddNote").click(function() {
alert("knock knock");
var gnote = getNotes();
//var notes = $("#txtNote").val();
if (gnote == null) {
alert("Note is null");
return;
}
$.post("Documents/AddNote", gnote, function(data) {
var msg = data.Msg;
$("#resultMsg").html(msg);
});
});
});
function getNotes() {
alert("I am in getNotes function");
var notes = $("#txtNote").val();
if (notes == "")
alert("notes is empty");
return (notes == "") ? null : { Note: notes };
}
</script>
</asp:Content>
Something like this would give you the ability to send data to an action do some logic and return a Json result then you can update your View accordingly.
Javascript Function
function AddNote(){
var d = new Date(); // IE hack to prevent caching
$.getJSON('/MyController/MyAction', { data: "hello world", Date: d.getTime() }, function(data) {
alert(data);
// call back update your view here
});
}
MyController Action
public virtual JsonResult MyAction(string data)
{
// do stuff with your data here, which right now my data equals hello world for this example
return Json("ReturnSomeObject");
}
What you want is AJAX update. There will always be a postback (unless you are satisfied with simple Javascript page update that does not save on the server), but it won't be the flashing screen effect any more.

Resources