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 });
Related
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:
I have to know file downloaded status in clientside and I am using ASP.NET MVC to do the task. I cannot use cookies to know the status as the page is opening in iframe in some other application which doesn't allow me to keep cookies.
I would like to access the QueryString from RedirectToAction Url which is "DownloadUrl". My screenshot to get the value and respected view and controler code is as below. How can I achieve the "downloadStatus" querystring in my case? Please help.
Index.cshtml
#{
ViewBag.Title = "Home Page";
}
<script type="text/javascript">
$(document).ready(function () {
$("#download").on("click", function () {
$('#statusDiv').show();
setTimeout(checkDownloadStatus, 1000); //Initiate the loop to check the downloadStarted value.
});
var checkDownloadStatus = function () {
// Get querystring value for downloadStarted
if (getUrlParameter("downloadStatus") == 1) {
$('#statusDiv').hide();
} else {
downloadTimeout = setTimeout(checkDownloadStatus, 1000); //Re-run this function in 1 second.
}
};
// get querystring value
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
});
</script>
#using (Html.BeginForm(null, null, FormMethod.Post, new { #id = "formDownload" }))
{
<div class="row">
<div id="statusDiv" style="display:none;">File is downloading ...</div>
<button type="submit" formaction="~/Home/FileDownload" id="download" value="download" formmethod="post">
Download
</button>
</div>
}
HomeController.cs
using System.Threading.Tasks;
using System.Web.Mvc;
namespace RedirectToActionDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public async Task<ActionResult> FileDownload()
{
var fileStream = System.IO.File.ReadAllBytes(#"D:\Documents\Information.docx");
DownloadFileResult res = new DownloadFileResult();
res.FileResult = fileStream;
res.MimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
res.FileName = "Information.docx";
TempData["Result"] = res;
return RedirectToAction("downloadUrl", new { downloadStatus = "1" });
}
public ActionResult DownloadUrl(string downloadStatus)
{
DownloadFileResult res = TempData["Result"] as DownloadFileResult;
return File(res.FileResult, res.MimeType, res.FileName.Replace("\"", ""));
}
}
public class DownloadFileResult
{
public byte[] FileResult { get; set; }
public string FileName { get; set; }
public string MimeType { get; set; }
}
}
This should give you the last part of your url:
#{
var id = Request.Url.Segments.Last();
}
Some info about the above
I cant figured out how to show whole page after Ajax call to Controler. After 'Order' buton click I call javascript function where I make Ajax call to controler action to get XML in string and with that string I call another controller action where I return model. In last step I want to call third controller action with return View(model) but I get null object parameter.
function order(model) {
$('#details-container').html("<h2>Loading Complete Frame Module. Please wait...</h2>");
$.p({
url: '#Url.Action("CompleteFrameBrandDetails", "PacCompleteFrame")',
data: { item: model },
success: function (xml) {
if (xml.Success) {
$.p({
url: '#Url.Action("GlassCompleteFrame", "PacModule")',
data: JSON.stringify({ b2bXml: xml.Data }),
success: function (model) {
var pacModuleModel = {
CustomerNumber: model.Data.CustomerNumber,
Language: model.Data.Language,
Comission: model.Data.Comission,
GlassXml: model.Data.GlassXml,
Price: model.Data.Price,
ReadOnly: model.Data.ReadOnly,
Mode: model.Data.Mode,
IframeUrl: model.Data.Mode
};
var url = '#Url.Action("GlassCompleteFrameView", "PacModule", "__view__")';
window.location.href = url.replace("__view__", JSON.stringify(pacModuleModel));
}
});
} else {
$.alert({
message: 'error while trying to load xml details'
});
}
}
});
}
public ActionResult GlassCompleteFrame(string b2bXml)
{
string mode = "5";
//If the Store isn't selected, redirect to HomePage
if (string.IsNullOrEmpty(_workContext.SelectedCustomerNumber))
{
return RedirectToRoute("HomePage");
}
else
{
PacModuleModel model = new PacModuleModel();
model.CustomerNumber = _workContext.SelectedCustomerNumber;
model.Language = _workContext.WorkingLanguage.UniqueSeoCode;
model.Comission = "";
if (b2bXml == null || b2bXml == String.Empty)
{
return RedirectToRoute("HomePage");
}
else
{
model.GlassXml = b2bXml.Replace("\"", "\\\"");
}
int index = b2bXml.IndexOf("<price>") + "<price>".Length;
string p = b2bXml.Substring(index, b2bXml.IndexOf("</price>") - index);
model.Price = Convert.ToDouble(p, System.Globalization.CultureInfo.InvariantCulture);
model.ReadOnly = false;
model.Mode = ModuleMode.ByProduct;
model.IframeUrl = "http://ItkCompleteConfiEmbedded.aspx?lang=" + _workContext.WorkingLanguage.LanguageCulture; //_pacGeneralSettings.GlassModuleUrl + ;
return new JsonResult()
{
Data = new
{
Success = true,
Data = model
}
};
}
}
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get null model parameter
return View("Glass", model);
}
Curently I don't know how to pass model to the last action controller. Thank you nice people for help.
If I understand correctly, something like this should do the trick:
Let's say you have, in your controller MyModelController:
public ActionResult SomePage(MyModel myModel){
return View(myModel);
}
To naviguate to that page, you could do:
<script>
window.location.href = "#Url.Action("SomePage", "MyModel", myModelObject)";
</script>
I hope this helps!
I use Session variable to get model in GlassCompleteFrameView(PacModuleModel model) and works perfect. I set Session variable in public ActionResult GlassCompleteFrame(string b2bXml).
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
model = Session["xml"] as PacModuleModel;
return View("Glass", model);
}
I want URL by #URL.Action with Parameter.
Here is my code but i am getting blank value from it.
Script
var OpenURL = ' #Url.Action("Document", "Controller", new { ID= "-22" })';
alert(OpenURL); // Value of this is coming blank
Controller.cs
public ActionResult Document(int? ID)
{
return View();
}
Route.cs
routes.MapRoute("Document", "OpenDocuments/{ID}", new { controller = "Controller", action = "Document", ID= UrlParameter.Optional });
please help me out!!
Thanks!!
ControllerController.cs
public class ControllerController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Document(int? ID)
{
return View();
}
}
Index.cshtml:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script>
var OpenURL = ' #Url.Action("Document", "Controller", new { ID= "-22" })';
alert(OpenURL); // Value of this is coming blank
</script>
Works in my case.
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();
}