Updating view by calling Action Method from Javascript - javascript

I have a javacript Like this:
<script>
function GetFromDate() {
var dt1 = document.getElementById('fromDate').value;
var dt2 = document.getElementById('toDate').value;
var url = "Statistics/Excel/" + dt1 + "!" + dt2;
window.location.href = url;
return false;
};
</script>
and in controller my ActionResult is like this:
public ActionResult Excel(string id)
{
\\ View Creation
if(SomeLogic)
{
\\Excel Download Options
}
return View(viewModel);
}
Though it is perfectly working with the Excel Downloading option but it is not returning the View. Any Suggestions?
For more information "viewModel" object contains the perfect data to be displayed.

If your response is returning a file download, then this counts as your Http response, you aren't able to then do a redirect in the same action.

Related

Pass a value to my controller with $.get() javascript to my controller method

Here is my goal:
I'm trying to display the details of an event in my modal.
For that, I execute a javascript script which returns to the "GetEventsDetails" method of my "Event" controller with the id of the event.
When I debug with Chrome, I see the id pass except that in my controller, the value is always 0.
I do not really understand why, I checked a lot on the net and everything seems right on my side!
Is it because I do not use an ajax call?
Thank you in advance!
function GetEventsDetails(id) {
//$('#myModal').find('.modal-title').text("Details ");
$.get("#Url.Action("GetEventsDetails", "Events")/" + id,
function (data) {
$('.modal-body').html(data);
})
$('#myModal').show();
}
</script>
}
[Authorize]
[HttpGet]
public async Task<ActionResult> GetEventsDetails(int Zkp)
{
ViewBag.sessionv = HttpContext.Session.GetInt32("idMember");
FileMakerRestClient client = new FileMakerRestClient(serverName, fileName, userName, password);
var toFind = new Models.EventsLines { Zkp = Zkp };
var results = await client.FindAsync(toFind);
bool isEmpty = !results.Any();
if (isEmpty)
{
return View();
}
Models.EventsLines oEventViewModel = new Models.EventsLines();
oEventViewModel = results.ToList().First();
Console.WriteLine(oEventViewModel);
return PartialView(oEventViewModel);
}
<script>
function GetEventsDetails(id) {
//$('#myModal').find('.modal-title').text("Details ");
var urlpath = "/ Events / GetEventsDetails /" + id;
$.get(urlpath, function (data) {
$('.modal-body').html(data);
});
$('#myModal').show();
}
</script>
And Your Controller
public async Task<ActionResult> GetEventsDetails(int id)

Not Showing the output of Json Data from controller to the view

I am trying to to show the Json data from controller to the view. It works fine in my test project, but when I copied the work in the main project it gives error.
It says Url does not exist in the current context. Although it works fine in the test project and doesn't give this error.
Controller Code -
public JsonResult GetFreight()
{
string url = "https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate.json?length=22&to_postcode=3000&from_postcode=2000&weight=1.5&height=7.7&width=16&service_code=AUS_PARCEL_REGULAR";
//synchronous client.
var client = new WebClient();
client.Headers.Add("auth-key:a1234567-abcd-abcd-1234-1234567890abc");
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return Json(jsonContent, JsonRequestBehavior.AllowGet);
}
View Code
<script>
var weather = Object();
$(document).ready(function () {
$.get("#Url.Action("GetFreight", "ShoppingCart")", function (response) {
//response
console.log(response);
weather = ko.mapping.fromJS(response); //populate the weather object
ko.applyBindings(weather);
});
});
</script>
<td>Freight = <span data-bind="text:postage_result.total_cost"></span></td>
I want to mention one more thing- In the main project the view is placed in another subfolder called "ShoppingCart" so do I need to change anything in the script when calling the method from the controller? Any help will be appreciated.
Thanks.

Pasing Javascript result to View

I got a Question, I'm really new in working with Asp.net.
I got a Javascript where I woult like to pass Data to my Controller.
<script type="text/javascript">
$("#SearchButton").on("click", function () {
var $sucheMoped = [];
$("#tab_logic tbody tr")
.each(function () {
var $Item = $(this);
var suchfeld = $Item.find("td > input[name='Suchfeld']").val();
var schluessel = $Item.find("td > select[name='Suchschluessel'] > option:selected").val();
alert(suchfeld + "&&&" + schluessel);
$sucheMoped.push({
Suchfeld: suchfeld,
Suchschluesseltyp: schluessel
});
});
window.open('#Url.Action("MainView","MainView")?SuchObject='+$sucheMoped);
})
</script>
I just would like to pass the "sucheMoped" from my javaScript to my Controller.
My Controller is just expecting a IEnumarable of Objects with Properties Suchfeld and Suchschluesseltyp.
Anyone an idea?
Thanks Guys.
First of all, you need to change the way you invoke the controller action. You should stringify the array using the JSON.stringify() method.
So, this should look like this:
window.open('#Url.Action("MainView","MainView")?SuchObject='+JSON.stringify($sucheMoped));
Then, you need to create a custom model binder to bind your array with the action parameter. This is a simple array model binder for demonstration purposes only, it doesn't take into account failures or whatever, but it works in this scenario, passing the correct data, so please modify it to fit your needs.
public class ArrayModelBinder: DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var rawArray = controllerContext.HttpContext.Request.QueryString["SuchObject"];
var array = JsonConvert.DeserializeObject<IEnumerable<MyObject>>(rawArray);
return array;
}
}
What I do here, is to get the query string submitted through the URL, convert it with JsonConvert.Deserialize<T> method and return it.
You simply need to decorate your parameter in the controller's action with the custom model binder, like this:
[HttpGet]
public ActionResult Search([ModelBinder(typeof(ArrayModelBinder))]IEnumerable<MyObject> SuchObject)
{
return View(SuchObject);
}
Edit
window.open is useful if you want to open a new browser window. You could use it to open a new tab as well.
In order to navigate to another location without opening a new tab or window, use the window.location property like the following:
window.location = '#Url.Action("Search", "Home")?SuchObject=' + JSON.stringify(array);
If you use the jQuery.ajax method, you can pass complex objects as data parameter.
$.ajax({
url: '#Url.Action("MainView", "MainView")',
type: 'GET',
data: { 'SuchObject': $sucheMoped },
success: function (htmlContent) {
// write content to new window (from http://stackoverflow.com/a/23379892/1450855)
var w = window.open('about:blank', 'windowname');
w.document.write(htmlContent);
w.document.close();
}
});
You can use jquery library $.getScript to call the action method in your controller and the return javascriptResult type in your action.
$.getScript("Home","Display")
// Home Controller
private JavaScriptResult Display()
{
string message = "alert('Hello World');";
return new JavaScriptResult { Script = message };
}

Export CSV using jQuery AJAX call

I have some code to export the results of a search to a CSV file:
$("#exportButton").click(function () {
var url = "/Stuff/ExportSearchResults";
var searchInput = readInput();
$.post(url, searchInput, function (data) {
// This is where I'm clueless.
// I'm getting data back but not sure how to make the
// browser show a prompt to download the file.
console.log(data);
});
});
At the server side (ASP.NET MVC 4) there's this:
[HttpPost]
public FileResult ExportSearchResults(SearchInput model)
{
string csv = GenerateCsv(model);
return File(new UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
}
So the good thing is that I'm getting data back in the console. I'm just not sure how I would make the browser show a prompt to download a file.
Here for this question we can go with comment from https://stackoverflow.com/users/5349021/sreepathy-sp
At Client side
$("#exportButton").click(function () {
var url = "/Stuff/ExportSearchResults";
var searchInput = readInput();
window.location.href = '/Stuff/ExportSearchResults?searchInput='+searchInput ;
});
At server side
[HttpGet]
public FileResult ExportSearchResults(string model)
{
string csv = GenerateCsv(model);
Stream stream = new MemoryStream(new UTF8Encoding().GetBytes(csv));
return File(stream , "text/csv", "Export.csv");
}
Hope this will help you out.

Window.location.href post parameters to actionresult asp.net mvc

I try to post textbox value to actionresult in asp.net mvc
Javascript:
function OnButtonClick() {
var data= {
TextBox: TextBox.GetValue()
};
var PostData= data.TextBox;
window.location.href = "Home/MyActionResult?Page=data" + PostData;
}
ActionResult
public ActionResult MyActionResult(string PostData)
{
return view();
}
Whenever I post data to Home/MyACtionResult , PostData is always null,
What am I missing ?
How can I post textbox value to actionresult?
Try with this:
window.location.href = "Home/MyActionResult?Page=data&PostData=" + PostData;
Try this
var url = '#Url.Action("../Home/MyActionResult")' + '?Page='+data+'&'+PostData;
window.location.href = url;
This type of passing data is a bad approach. Please try to look into another code approach. This will not work for huge data, urls, secured data.
With window.location.href you can't use POST method.
But here is simple trick if you don't want to you GET method.
You can use cookies and then
function OnButtonClick() {
setCookie("param1",value1,30);
setCookie("param2",value2,30); // and so on, fetch input names and values using javascript
window.location.href = "Home/MyActionResult"
}
And then you can get cookies values from your MyActionResult page and use it.
Ofcource you have to include setCookie function as well in your page.

Categories

Resources