How to pass JS data from script file to C# method - javascript

I've been wracking my brain over this problem for a while. How can I invoke a JS function and retrieve the data to be used within a C# method?
Should I be using ViewBag in this example?
.cshtml
<script>
function somefunction(str)
{
//use str within Index() method
return str;
}
</script>
Controller
public IActionResult Index()
{
//use the data within this method
return View();
}

Have you tried this
In javascript function:
//Do your action
window.location.href = '#Url.Action("Index", new { value = 1})';
and modify the Index Action to accept parameter like this:
public ActionResult Index(int value)
As your Index returns a View, window.location.href will basically redirect to Index action.
You can also create an url using string concatenation in javascript and use that url to redirect.
In my case the #Url.Action converts to this URL : '/Home/Index?value=1'.

Related

Passing value from QueryString into Index action of controller in asp.net mvc

I have a querystring like this:
http://localhost:2563/Skill?Months=1,2,3,4,5,6,7,8,9,10,11,12&SelectedMonth=8&Year=2016,2017,2018&SelectedYear=2016&....
And I want to pass Months, SelectedMonth, Year, SelectedYear value into Index() of controller (Index is a function takes 0 argument).
And another issue, after Index function completed, I want binding function (in javascript) to run to bind value into dropdownlist by the SelectedMonth, SelectedYear in querystring
Please help. This function helps access the Views by QueryString (not through my website)
Many thanks.
First, the action name is wrong. you should use the following,
http://localhost:2563/index?Months=1,2,3,4,5,6,7,8,9,10,11,12&SelectedMonth=8&Year=2016,2017,2018&SelectedYear=2016&...
instead of
http://localhost:2563/Skill?Months=1,2,3,4,5,6,7,8,9,10,11,12&SelectedMonth=8&Year=2016,2017,2018&SelectedYear=2016&....
second,
You need to pass some parameters.
Here is how:
public ActionResult Index(List<int> Months,int SelectedMonth,List<int> Year, int Year)
{
}
remember to pass values as you wish to work with them. if you don't, you will face some error. use try catch block to prevent and handle exceptions.
You may also face exception accessing the web page. try to put optional parameter instead of using the above one.
public ActionResult Index(List<int>? Months,int? SelectedMonth,List<int>? Year, int? Year)
{
}
public ActionResult Index(List<int> Months,int SelectedMonth,List<int> Year, int Year)
{
}
or use Reqest.QueryString
public ActionResult Index()
{
var months=Reqest.QueryString["Months"];
.
.
.
}
You need to get parameters from here HttpContext.Current.Request.QueryString

How to control function called by this.form.submit in mvc

I am using Telerik.MVC extensions and certain controls to not pass data to the controller on events.
Tee dropdown must call this.form.submit during an OnChange event to register that the user made a selection.
function ddl_OnChange(e)
{
this.form.submit();
}
In the controller I have:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind()] ViewModel.Designer model, string ddlDatabase,
string ddl, string cboTemplate, string command)
{
if (ModelState.IsValid)
{.....
On the OnChange, the value of the ddl control is passed through the ddl value.
My problem is, I have multiple dropdown and combos and would like to control the action taken by the controller depending on the choice made. How can I direct the this.form.submit();
to other functions. Also, how can I pass data additional data back to this other method.
Solution:
In the script, set the action property:
function ddlTable_OnChange(e)
{
this.form.action += '\\ddlTable_OnChange';
this.form.submit();
}
In the controller, create matching function:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ddlTable_OnChange([Bind()] ViewModel.Designer model, string ddlDatabase,
string ddlTable, string cboTemplate, string command)
{
return Index();
}

Custom action result return specific view in MVC C#

I have an MVC application which i am trying to give the user the opportunity to download a zip of files,but unsuccesfully.Let me explain further.
Inside my view(ImageViewer.cshtml) i have a div class with an on click event that when pressed i call the controller method(ImageViewerController.GetZipPhotos) which handles the download of the zip file.See below:
div class="text" onclick="GetZipPhotos()">Download</div>
and the Javascript that get called is this:
function GetZipPhotos() {
$.ajax({
url: '#Url.Action("GetZipPhotos", "ImageViewer",Request.Url.Scheme)',
type: 'POST',
contentType: 'application/zip',
error: function () {
alert('There was an error!'+result);
}
});
}
Now, inside my ImageViewerController i have the following method:
[HttpPost]
public ActionResult GetZipPhotos()
{
ZipResult newZipResult=new ZipResult(
Server.MapPath("~/File1.txt"),
Server.MapPath("~/File2.txt")
);
newZipResult.OutPutZipFileName = "PhotosZip.zip";
return newZipResult;
}
and the declaration of the ZipResult custom action is:
public class ZipResult:ActionResult
{
private IEnumerable<string> _filesToZip;
private string _outPutZipFileName="ZipFile.zip";
public ZipResult(params string[] filesToZip)
{
this._filesToZip = filesToZip;
}
public override void ExecuteResult(ControllerContext context)
{
using (ZipFile oneZipFile = new ZipFile()) {
oneZipFile.AddFiles(_filesToZip);
context.HttpContext.Response.ContentType = "application/zip";
context.HttpContext.Response.AppendHeader("content-disposition", "attachment; filename=" + _outPutZipFileName);
oneZipFile.Save(context.HttpContext.Response.OutputStream);
}
}
}
The problem is that the code ofcourse doesn't work because the name of the view that called the controller is different from the actual method(GetZipPhotos).The view's name is ImageViewer.cshtml and the controller's name is ImageViewerController.
As fas as i have understood, the MVC framework uses code conventions, so it expects the name of the method to be the same as the view.The problem is that my view and the method are diferrent so the response never gets to back to the view.
I thought of creating a new view that has basically nothing inside, just to call it from the method and return the zip file.If this could be a possible solution, how can i tell from the action result which view to send the response?
No need to use ajax for the file download. The browser will normally start the download and keep you on the same page. Also, no need for a custom action result, you can just use FileResult. Try something like this:
public FileResult GetZipPhotos()
{
var filesToZip = new List<string> { Server.MapPath("~/File1.txt"), Server.MapPath("~/File2.txt") };
var oneZipFile = new ZipFile();
oneZipFile.AddFiles(filesToZip);
return File(oneZipFile.ToByteArray(), "application/zip", "PhotosZip.zip");
}
Of course, you'll need to figure out this part oneZipFile.ToByteArray(), but the ZipFile class probably already has something like that.
Your ajax call is redirecting the response into nowhere.
I would do it like this:
use a hidden iframe, change its src to the desired path in your function and it should be prompting a file dialog.

URL string parameters passed to MVC controller action arrive as null

Have Controller:
public class MyController : Controller
{
[HttpGet]
public ActionResult MyAction(int iMode, string strSearch)
{
return View();
}
}
In my view I have a div with id=center
I execute the following code in javascript
url = "/MyController/MyAction?iMode=7&strSearch=as";
$('#center').load(url);
When debugger his the breakpoint in my action on first line, iMode variable shows proper value of 7, strSearch parameter arrives as null.
Any help/advice would be most welcome.
Just use the ampersand instead of &
url = "/MyController/MyAction?iMode=7&strSearch=as";
Thanks Innatepirate for the tip. Wasted enough time trying to figure out why controller is getting null values. Replacing & with ampersand did the trick. By the way I was doing the simple age old window.location.href = link and still had the problem. Probably its the MVC parsing and routing that is messing this up.

ASP.NET MVC - Return JavascriptResult and Json parameter

Here is the scenario
In MVC, it is easy to return a Javascript to be executed on the client
public ActionResult DoSomething()
{
return JavaScript("alert('Hello world!');");
}
On the client, I have a Javascript that takes a JSon object as parameter
Something similar to this :
function open(options) {...}
I wanted to call this function from my action passing it a json object generated on the server
so I wrote this
public ActionResult DoSomething()
{
var viewData = new {...};
return JavaScript( "open('" + Json(viewData) + "')" );
}
However, when my Javascript function get called, I don't get any data but this: open('System.Web.Mvc.JsonResult')
I will appreciate any help on this matter
Thanks
The Json method returns a JsonResult. Not a JSON string. You could use the JavaScriptSerializer
public ActionResult DoSomething()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
var viewData = new {...};
return JavaScript( "open('" + serializer.Serialize(viewData) + "')" );
}
Depending on how your client side open method works you may need to send the json data as a json object instead of a string by simply removing the ' around the method argument.

Categories

Resources