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.
Related
I am having trouble passing data from my view to my controller. I am using checkboxes. For my view, I created a class that takes in all my checkboxes (Mon-Fri) and putting them into a list (so I can use the data someplace else). My problem is that when I debug and click the checkboxes on the website, the code does not change whether I click the checkbox or not, so my code doesn't recognize the checkbox data
I'm not sure if I have implemented the View incorrectly but any help to the right direction would be appreciated !
ViewModel:
public List<cDay> _cDays = new List <cDay>();
public List<cDay> cDays
{
get {return _cDays;}
set {_cDays = value;}
}
public class cDay
{
public bool Monday { get; set; }
public bool Tuesday { get; set; }
public bool Wednesday { get; set; }
public bool Thursday { get; set; }
public bool Friday { get; set; }
}
CSHtml file:
#Html.Label("M")
#Html.CheckBox("Monday", false, new { #class = "availability" })
// this is basically the same code for Tuesday-Friday as well.
'<label for="M">M</label> +
'<input class="availability" id="Monday" name="Monday" type="checkbox" value="true">' +
'input name="Monday" type="hidden" value="false">'
// this is basically the same code for Tuesday-Friday, but the "name" corresponds to each day
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string inputValue, Model viewModel)
{
if(ModelState.IsValid)
//
}
Consider to use the following data model:
public class DaysViewModel
{
public List<CDay> Days { get; set; } = new List<CDay>();
}
public class CDay
{
public CDay()
{
Name = string.Empty;
Selected = false;
}
public CDay(string name)
{
Name = name;
Selected = false;
}
[Required]
public string Name { get; set; }
[Required]
public bool Selected { get; set; }
}
Then you can use the default ASP.NET MVC data binding without a JS support:
#model Models.DaysViewModel
#using (Html.BeginForm("Edit", "Home"))
{
#Html.AntiForgeryToken()
for(int i=0; i < Model.Days.Count; i++)
{
<div class="form-group row">
#Html.CheckBox("Days[" + i + "].Selected", Model.Days[i].Selected)
#Html.Hidden("Days[" + i + "].Name", Model.Days[i].Name)
<span>#Model.Days[i].Name </span>
</div>
}
<input type="submit" value="Save" />
}
And on the server side:
public ActionResult Edit()
{
var model = new DaysViewModel();
model.Days.AddRange( new List<CDay> {
new CDay("Monday"),
new CDay("Tuesday"),
new CDay("Wednesday"),
new CDay("Thursday"),
new CDay("Friday")
});
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(List<CDay> days)
{
if(ModelState.IsValid)
{
// ... you_code here
}
var model = new DaysViewModel() { Days = days };
return View(model);
}
Test screen shots
The view:
On the controller side:
You can do it using jQuery
Add a button bellow your checkboxes
<input type="button" value="Your_Value" class="btn btn-default" />
When click on a button create a post request and sends checked status via querystring
$(document).ready(function () {
$("input[type=button]").click(function () {
var queryString = 'Monday=' + $("input[name=Monday]").is(":checked") + '&Tuesday=' + $("input[name=Tuesday]").is(":checked") + '&Wednesday=' + $("input[name=Wednesday]").is(":checked") + '&Thursday=' + $("input[name=Thursday]").is(":checked") + '&Friday=' + $("input[name=Friday]").is(":checked");
$.ajax({
type: "Post",
url: "/Home/Edit?" + queryString,
success: function (data) {
},
error: function (data) {
}
});
});
});
And inside controller create Edit Post Method like this
[HttpPost]
public ActionResult checkboxespost(string Monday, string Tuesday, string Wednesday, string Thursday, string Friday)
{
...
}
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 know that a very similar question was posted and ansered:
How to gracefully handle AJAX PartialView update when Javascript is disabled
But that solution isnt satisfying me.
Is it possible, to update a Element with the Ajax Helper Method when Java Script is disabled, that it will show a partial view in the same page and not in an extra tab?
I want that the Tag in the Index View is updated with a partial View (_Details), when I click on a AJAX ActionLink.
With the PView 1 Method, I get the same result with JS enabled and disabled. But i dont linke the PView 1 solution (as suggested in the similar question), because this makes the Partial View Class useless. Why would i need it when i reload the hole page anyway.
I would prefer a solution similar to PView 2. But there the Partial View is opened in a new Tab when JS is disabled.
My very simplified code so far:
HomeController Class
public class HomeController : Controller
{
public ActionResult Index()
{
var obj_str = new SimpleString { astr = "Nothing Yet" };
return View(obj_str);
}
public ActionResult PView1()
{
string str_posted = "String of PView 1";
var obj_str = new SimpleString {astr = str_posted};
if (Request.IsAjaxRequest())
{
return PartialView("_Details", obj_str);
}else
{
return View("Index", obj_str);
}
}
public PartialViewResult PView2()
{
var obj_str = new SimpleString {astr = "String of PView 2"};
return PartialView("_Details", obj_str);
}
}
Index.cshtml
<h2>AJAX Actionlink Index</h2>
#Ajax.ActionLink("Click me for PView 1", "PView1", new AjaxOptions
{
UpdateTargetId = "partv",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
#Ajax.ActionLink("Click me for PView 2", "PView2", "Home", new AjaxOptions
{
UpdateTargetId = "partv",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
<h3>Partial View here!</h3>
<div id="partv">
<p>#Model.astr</p>
</div>
_Details.cshtml (the Partial View)
#model MVCPartialViewTest.Models.SimpleString
<p>This is from the Partial View cshtml</p>
<p>#Model.astr</p>
SimpleString Class (the Model)
public class SimpleString
{
public string astr { get; set; }
}
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 });