Calling Javascript function - javascript

Extending a website I didn't build. I want to be able to call the ShowWindow proc with a parameter. How would I do that? New to JQuery and Javascript.
default.aspx
<script type="text/javascript" src="/scripts/jquery-1.2.6.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('a#ShowWindow').click(function() {
window.open("TerminalInfo.aspx?", 'Info', 'scrollbars=yes,width=510,height=536');
})
});
default.aspx.cs
Building the aspx dynamically...
public static string ToHtml(this Location location)
{
var html = new StringBuilder();
html.Append("<td><a href='#' id='ShowWindow'>ShowLetter</a></td>"); //This works
html.Append("<td><a href='#' id='ShowWindow(\"MyInfo.aspx\")'>Read More</a></td>"); //How can I do this? It doesn't work.
return html.ToString();
}

public static string ToHtml(this Location location)
{
var html = new StringBuilder();
html.Append("<td><a href='MyInfo.aspx' id='ShowWindow'>Read More</a></td>");
return html.ToString();
}
and then
$('a#ShowWindow').click(function(e) {
window.open($(this).attr("href"), 'Info', 'scrollbars=yes,width=510,height=536');
e.preventDefault();
})
It's a little different approach but it degrades better if JavaScript is unavailable.
Update (to work on several links in table)
$('table a').click(function(e) {
window.open($(e.target).attr("href"), 'Info', 'scrollbars=yes,width=510,height=536');
e.preventDefault();
});

var strattonn = {};
strattonn.openWindow = function(url, title) {
window.open(url, title, 'scrollbars=yes,width=510,height=536');
return false;
}
public static string ToHtml(this Location location)
{
var html = new StringBuilder();
html.Append("<td><a href='#' onclick='return strattonn.openWindow('MyInfo.aspx', 'My Info')'>Read More</a></td>");
return html.ToString();
}

Related

How can I return javascript from a controller actionresult using ContentResult?

I'm wondering how I can return a javascript alert when the file that usually gets generated is not created in the folder. When the else statement is ran, it returns the literal text at the top of the browser tab instead of the alert that I am looking for. It looks like this:
Code:
public ActionResult DownloadFile(string path, string fileName)
{
if (System.IO.File.Exists(path))
{
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
return File(fileBytes, "application/force-download", fileName);
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('No data was found to create a CSV file!');</script>");
}
}
Firstly you can use the method public virtual ContentResult Content(string content, string contentType); rather than public virtual ContentResult Content(string content);
Controller:
public ActionResult DownloadFile()
{
return Content("alert('No data was found to create a CSV file!');", "application/javascript");
}
In addition,you can also write a result which has a Parametrical constructor and extends ContentResult.You can refer to it
Here is a demo worked:
Controller:
public ActionResult DownloadFile()
{
//return Content("alert('No data was found to create a CSV file!');", "application/javascript");
return new JavaScriptResult("alert('No data was found to create a CSV file!');");
}
public ActionResult DownloadFile1() {
return View();
}
public class JavaScriptResult : ContentResult
{
public JavaScriptResult(string script)
{
this.Content = script;
this.ContentType = "application/javascript";
}
}
DownloadFile1:
#{
ViewData["Title"] = "DownLoadFile1";
}
<h1>DownLoadFile1</h1>
<div>
<partial name="DownLoadFile" />
</div>
#section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$.getScript("/Test/DownloadFile");
});
</script>
}
Result:

MVC, how get model property from response viewModel

I am implementing "show more posts" in my blogs list following
this example but I want to make a change and switch from using ViewData to ViewModel.
This the relevant code:
private void AddMoreUrlToViewData(int entryCount)
{
ViewData["ShowMore "] = Url.Action("Index", "Messaggi", new { entryCount = entryCount + defaultEntryCount });
}
that I switch to
ViewModel.ShowMore = Url.Action("Index", "Messaggi", new { entryCount = entryCount + defaultEntryCount });
the Index action of the example:
public ActionResult Index(int? entryCount)
{
if (!entryCount.HasValue)
entryCount = defaultEntryCount;
int totalItems;
if(Request.IsAjaxRequest())
{
int page = entryCount.Value / defaultEntryCount;
//Retrieve the page specified by the page variable with a page size o defaultEntryCount
IEnumerable<Entry> pagedEntries = GetLatestEntries(page, defaultEntryCount, out totalItems);
if(entryCount < totalItems)
AddMoreUrlToViewData(entryCount.Value);
return View("EntryTeaserList", pagedEntries);
}
//Retrieve the first page with a page size of entryCount
IEnumerable<Entry> entries = GetLatestEntries(1, entryCount.Value, out totalItems);
if (entryCount < totalItems)
AddMoreUrlToViewData(entryCount.Value);
return View(entries);
}
Here I add a lot of code to load the post from the db, the only code I think is relevant is that I swtich return View("EntryTeaserList", pagedEntries); to return View(myViewModel); after setting BlogsList and ShowMore property.
But my problem is in the javascript command:
$(function() {
addMoreLinkBehaviour();
});
function addMoreLinkBehaviour() {
$('#entryTeaserList #moreLink').live("click", function() {
$(this).html("<img src='/images/ajax-loader.gif' />");
$.get($(this).attr("href"), function(response) {
$('#entryTeaserList ol').append($("ol", response).html());
$('#entryTeaserList #ShowMore').replaceWith($("#ShowMore", response));
});
return false;
});
}
where
$('#entryTeaserList #ShowMore').replaceWith($("#ShowMore", response));
to take ViewData property and use it to replace the link.
How can I read the ViewModel Property instead?

why these cookie codes didn't work in asp.net mvc?

I'm developing an asp.net mvc 5 online store project . I want to create cart to add Goods with Cookie . I'm confused about it and don't know why it didn't work . it didn't gave me any error . also I add break points to debug it but any data didn't send to my actions !
could anyone help me ? what's the problem ?
I'm not good in javascript and I think problem would be in javascript codes :/
Thanks in advance
Goods controller
[HttpPost]
public ActionResult AddToCart(int Id, int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product added to your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("product didn't add to your basket", MessageType.Error).Script,
Html = ""
});
}
}
public ActionResult RemoveCart(int Id)
{
try
{
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
Request.Cookies["NishtmanCart_" + Id.ToString()].Expires = DateTime.Now.AddDays(-1);
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product removed from your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
else
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("this product doesn't have in your basket", MessageType.Warning).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product didn't remove from your basket", MessageType.Error).Script,
Html = ""
});
}
}
MyJsonData.cs
public class MyJsonData
{
public string Script { get; set; }
public string Html { get; set; }
public bool Success { get; set; }
}
_GoodDetailsAjax.cshtml
#foreach (var item in Model.GoodDetails)
{
<div>
<p class="nowprice">NowPrice : #item.DetailsNowPrice</p>
<p class="preprice">PrePrice : #item.DetailsPrePrice</p>
<a class="button icon-cart" href="#" GoodID="#item.DetailsGoodID">Add to cart</a><br>
<a class="link" >Shopping Cart (0)</a>
</div>
}
#section scripts{
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script>
$(function () {
$("a.button.icon-cart").click(function (e) {
e.preventDefault();
var goodId = $(this).attr("GoodID");
alert(goodId); //////// I just added this code
$.ajax({
url: "/Goods/AddToCart",
data: { Id: goodId, Count: 1 },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("Error!");
}
});
});
});
</script>
}
I don't know what's the implementation of MessageBox.Show("....", MessageType.Error).Script but I'm assuming that it just generates a simple JavaScript statement like this:
Script = "alert('product added to your basket');"
So you can add this tag for the result:
<div id="CartItems">
</div>
Now it works without any problem.
All of my codes was true , I just made some simple mistakes .
I loaded a JQuery file in my layout and also I loaded another version of JQuery in my view! I deleted one of them .
And also I used those codes in a partial view and loaded they using Ajax but my partial view couldn't pass data to Controller , I moved codes to main view (GoodDetails.cshtml) and it works fine now .

calling non static method from javascript

Hi my function is where i need to upload a xml file and check in the folder the file exist or not.
If the file exist i need to replace the file with a pop up in javascript by using ok or cancel and then from the button click i need to save the xml file and bind in a grid. Now im able to save the file but im not able to bind into the grid. Thanks.
My File upload code
if (FileUpload1.HasFile){
if (FileUpload1.PostedFile.ContentType == "text/xml")
{
string filename = Path.GetFileName(FileUpload1.FileName);
string path = Server.MapPath(ConfigurationManager.AppSettings["Path"]) + filename;
if (File.Exists(path))
{
ScriptManager.RegisterStartupScript(this, GetType(), "", "ConfirmBox();", true);
ExistPath = path;
Session["FileUpload1"] = FileUpload1;
Session["GridView1"] = GridView1;
}
else
{
SaveXml(path);
}
}
}
Javascript
<script language="javascript" type="text/javascript">
function ConfirmBox() {
if (confirm("Do you want to overrite")) {
PageMethods.FileExist(document.getElementById('<%=hfConfirmValue.ClientID %>').value);
}
}
</script>
The page method
[WebMethod(EnableSession = true)]
public static string FileExist(string confirm)
{
#region Save XML
string path = ExistPath;
FileUpload s = HttpContext.Current.Session["FileUpload1"] as FileUpload;
GridView g = HttpContext.Current.Session["GridView1"] as GridView;
s.SaveAs(path);
DataSet ds = new DataSet();
ds.ReadXml(Path.GetFullPath(path));
GlobalDS = ds;
g.DataSource = ds;
g.DataBind();
return "file updated";
#endregion
}

Assigning javascript value to Controller variable in ASP.NET MVC View

I try to assign javascript variable contentArea to content.Contents in my controller. How can I do that?
<script language="javascript" type="text/javascript">
$("#btnTest").click(function () {
var contentArea = tinyMCE.get("modalTextarea").getContent();
});
</script>
Action:
[HttpPost]
public ActionResult Index(string test)
{
DBEntities dbTest = new DBEntities();
tbl_Contents content = new tbl_Contents();
content.RegisterDate = DateTime.Now;
content.Title = "test";
content.Contents = "content1";
content.ImagePath = "image0";
dbTest.AddToICE_tbl_Contents(content);
dbTest.SaveChanges();
return View();
}
You need to send an AJAX request to the action's URL containing the data:
$.post("#Url.Action("Index")", { test: contentArea });

Categories

Resources