MVC button onClick - c#

I am making my MVC application. How do I create a button in my view that a click on it will run a function from controller. I would also like to pass data from the view that the button is in. But I do not want to open a different view. I just want to run a function - Button "save to file" would save the table from the view into a file - would open a Directory browser and save a file on a disk.

This will be done with the help of ajax request from your view. You need to add a simple button on your view and call a jquery function on its onclick event like this:
<input type="button" value="save to file" onclick="saveToFile()" />
Then you can create saveToFile function to send ajax request like this: here you can create your data as per your need of fields you want to post to controller. I just adding firstField and secondField for demo:
<script type="text/javascript">
var data = { "firstField" : "value1", "secondField": "value2" };
function saveToFile() {
$.ajax({
url: "/ControllerName/ActionName",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
success: function (data) {
},
error: function (xhr) {
console.log(xhr);
}
});
});
</script>
Your action method will be like this:
[HttpPost]
public ActionResult UseShippingAddress(string firstField, string secondField)
{
//write your logic here to save the file on a disc
return Json("1");
}

Apparently, the correct solution was to use
#Html.ActionLink("weekly - PDF", "GenerateTable", "Account", new { group_id = Model.group_id, class_id = Model.class_id, type = 1 }, null)
And in GenerateTable method just return a proper file.

Related

Using Action in Controller every 10min [duplicate]

I have sample code like this:
<div class="cart">
<a onclick="addToCart('#Model.productId');" class="button"><span>Add to Cart</span></a>
</div>
<div class="wishlist">
<a onclick="addToWishList('#Model.productId');">Add to Wish List</a>
</div>
<div class="compare">
<a onclick="addToCompare('#Model.productId');">Add to Compare</a>
</div>
How can I write JavaScript code to call the controller action method?
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
http://api.jquery.com/jQuery.ajax/
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter
window.location.href = '#Url.Action("Action", "Controller")/' + id;
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('#Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '#Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.
<div class="cart">
#Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>
That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on
If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action:
$(function(){
$('#sampleDiv').click(function(){
/*
While this code is JavaScript, but because it's embedded inside
a cshtml file, we can use Razor, and create the URL of the action
Don't forget to add '' around the url because it has to become a
valid string in the final webpage
*/
var url = '#Url.Action("ActionName", "Controller")';
});
});
Javascript Function
function AddToCart(id) {
$.ajax({
url: '#Url.Action("AddToCart", "ControllerName")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': id },
success: function (results) {
alert(results)
},
error: function () {
alert('Error occured');
}
});
}
Controller Method to call
[HttpGet]
public JsonResult AddToCart(string id)
{
string newId = id;
return Json(newId, JsonRequestBehavior.AllowGet);
}
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
You can set up your element with
value="#model.productId"
and
onclick= addToWishList(this.value);
I am using this way, and worked perfectly:
//call controller funcntion from js
function insertDB(username,phone,email,code,filename) {
var formdata = new FormData(); //FormData object
//Iterating through each files selected in fileInput
formdata.append("username", username);
formdata.append("phone", phone);
formdata.append("email", email);
formdata.append("code", code);
formdata.append("filename", filename);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/InsertToDB');//controller/action
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//if success
}
}
}
in Controller:
public void InsertToDB(string username, string phone, string email, string code, string filename)
{
//this.resumeRepository.Entity.Create(
// new Resume
// {
// }
// );
var resume_results = Request.Form.Keys;
resume_results.Add("");
}
you can find the keys (Request.Form.Keys), or use it directly from parameters.
You can easily make a <a> link in your view.
<a hidden asp-controller="Home" asp-action="Privacy" id="link"></a>
then in you javascript code use this:
location.href = document.getElementById('link').href;

How to call C# method from Javascript in ASP.NET Core?

I have a username textbox in my Index.cshtml file and I want to check for matches in our Active Directory whenever the user changes the text inside the textbox and then maybe display it in a DropDownList, so the user can choose form it.
So I call a JavaScript function on the oninput event of the textbox and now the question is how do I call my C# method FindUser() in Index.cshtml.cs from that JS function? I have tried a lot of what I've read, ajax call doesn't work, adding [WebMethod] and making the method static doesn't work and most on the internet is on MVC which I'm not using.
Textbox in Index.cshtml:
<input type="text" class="form-control" oninput="findUsers()" />
JavaScript function:
function findUsers() {
$.ajax({
url: 'Index\FindUser',
success: function (data) {
alert(data);
},
error: function (error) {
alert("Error: " + error);
}
})
}
leads the browser to alert
Error: [object Object]
Method in Index.cshtml.cs:
public void FindUser()
{
// code
}
The method is not even called from the JS function.
Also I've read a few times that calling a C# method from the view is not the proper way of doing it. If so, how can I achieve my goal then?
I see you're using Razor pages. A method in razor page model is not a routed method (it can't be called by requesting a route), and that's why trying to send an ajax request to Index\FindUser won't work, and the error returned by server would be 404 not found.
Alternatively you can use razor page handlers.
In your Index.cshtml.cs rename the method FindUser() to OnGetFindUser() or OnGetFindUserAsync() if the method is an asynchronous method.
You can then call this method by sending a request to "Index?handler=FindUser".
// Note the difference in method name
public IActionResult OnGetFindUser()
{
return new JsonResult("Founded user");
}
function findUsers() {
$.ajax({
type: 'GET',
// Note the difference in url (this works if you're actually in Index page)
url: '?handler=FindUser',
success: function (data) {
alert(data);
},
error: function (error) {
alert("Error: " + error);
}
})
}
Further suggested read
I am not very experienced yet, I have only started programming last year, but I hope I can help a little bit.
I also had a similar problem, but I could not execute a function directly from JavaScript. You could maybe create an API call to C# and make the API execute the function you want, and then return the data back to the client.
If I don't misunderstand, you want the user to type some text, and then return from your database a list based on the typed text.
You could use an onChange in the input tag, and each time it changes, it executes an API request to the server, which will search whatever you need and return it as a json. Then in JavaScript, you parse the data and put it in a select tag.
Hope it helps.
Ok so first off, you are calling jquery inside javascript function.
Calling a controller action method from ajax is pretty easy.
https://api.jquery.com/jquery.ajax/
You need to determine the request type, the url, the datatype returned, parameters passing etc and then set a breakpoint on the controller action and on the ajax request success and error functions. Then you will be able to see why it has succeeded or failed.
The way i would do it would be to give the input an id, then when a user types text catch the event.
https://api.jquery.com/category/events/
Don't confused jquery and javascript.
Jquery is a framework that packs javascript inside it.
Javascript is the native language.
You can use onkeyup or onblur like this
onblur: When you leave the input field, a function is triggered
onkeyup: A function is triggered when the user releases a key in the
input field
Then modify your code like this
html file:
<input type="text" class="form-control" id="username" oninput="findUsers()" />
js
function findUsers() {
var username= document.getElementById("username").value;
$.ajax({
type: 'GET',
url: '/Home/FindUser
dataType: 'json',
data: {username},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
}
You must return something like this. You are using void keyword so it will not return anything to FE side
public JsonResult FindUser(string username)
{
var object = {
// something here
}
return Json(object);
}
Change your API like this:
public bool FindUser(string value)
{
if (value == "Joe")
return true;
else
return false;
}
Then call it like this:
<script type="text/javascript">
function findUsers() {
var value = document.getElementById("value").value;
$.ajax({
type: 'GET',
url: '/Home/FindUser,
data: value,
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (error) {
alert(error);
}
});
}
</script>
<br />
<input type="text" class="form-control" id="value" oninput="findUsers()" />
you can call method exactly you want with
small addition to Index.cshtml. First line may be:
#page "{handler?}"
then call from ajax:
url:'/index/FindUser'
in Index.cshtml.cs calling method:
void OnGetFindUser(){}

Linkbutton equivalent in MVC C# Razor

I am converting a web form to MVC C# razor project. I like to know how I will get the same functionality in Razor where it will create a link and sumbit the form into the same page. The web form code is -
<asp:LinkButton ID="lnkBtn_1" runat="server" Text='<%#Eval("Sales") %>' OnCommand="LinkButton1_Command" CommandArgument='<%#Eval("Sales") %>' ></asp:LinkButton>
Thanks in advance
Try this
#Html.ActionLink("buttonText", "ControllerAction", "YourController ",
new { #sales = YourModel.Parameter}, new { #class =yourcssclass" })
Your Controller
public class YourController : Controller
{
public ActionResult Index()
{
var model = YourDataToDisplay;
return View(model);
}
public ActionResult ControllerAction(int sales)
{
//.....
}
}
You can use ViewData to define ButtonText.
There are many ways to use link button in rezor ,try any of these
<button type="button" onclick="#("window.location.href='" +#Url.Action("ActionResult", "Controller") + "'")">
Link Button
</button>
<a href="#Url.Action("ActionResult", "Controller")">
Link Button
</a>
#Html.ActionLink("Text","ActionResult","Controller")
submitting form into the same page you have to use Ajax Begin Form or use simple json object with a ajax post method. Try like this
$("#btnSave").click(function (e) {
var urlpath = '#Url.Action("ActionResult", "Controller")';
$.ajax({
url: urlpath ,
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error !!!");
}
});
You can write an anchor tag. But clicking on the anchor tag usually does not submit the form, but triggers an HTTP GET request. So you need to write some java script to do the form submission.
<form action="Customer/Create">
Submit
</form>
Using jQuery and some unobtrusive javascript code to bind the click event on this anchor tag,
$(function(){
$("#linkToSubmit").click(function(e){
e.preventDefault(); // prevent the normal link click behaviour (GET)
$(this).closest("form").submit();
});
});
Now you can execute the code in your HttpPost action of Create action method in the Customer controller (because that is the form's action set to)
Another option is to keep the submit button inside your form and style it so that it looks like a link as explained in this answer.
if you are new to mvc then you need to check it's basic from MVC tutorials: Please follow below thread for convert your web app code to MVC
https://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.actionlink(v=vs.118).aspx
#Html.ActionLink("buttonText",new { controller = "ContreollerName", action = "ActionName",
#sales = "Your parameter" })
And then make a action result in your controller

Redirect from partial view to view with json data object

I have a json data object which i need to pass from partial view to view with REDIRECT.
Lets say below is my partial view ( _createEmp.cshtml ):-
Note:- This partial view is in different view or page
<script type="text/javascript">
$(document).ready(function () {
LoadData();
});
function LoadData() {
$.ajax({
type: "GET",
url: baseURL + "Employee/GetEmpInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
console.log(data);
**EmpData** = data; // EmpData object
},
error: function (error) {
console.log("Error: " + error);
}
});
}
</script>
<div>
<input type="submit" value="Save" onclick="SetEmpInfo()" />
</div>
And i want to transfer EmpData object to a different view (lets say NewEmp.cshtml), bind something in that view from passed "EmpData object" and open that view (or REDIRECT to view NewEmp.cshtml).
As you are using ajax, you could return the URL from your action and have it redirected in javascript.
Without seeing your controller action you would need to do something like this:
Controller
public ActionResult GetEmpInfo()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("GetEmpInfoSuccess") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (data) {
if (data.success == true)
{
window.location = result.redirecturl;
}
}
Issuing a request to Employee/GetEmpInfo for getting the data and on success redirecting to other view - doesn't sound right
I think that you can do all this with one trip to server:
Write an Action that receives all the the parameters that GetEmpInfo receives. Lets call it NewEmployee.
If GetEmpInfo action is your code, reuse it's logic inside NewEmployee action to get EmpData. If it is not your code, you can use issue async request with HttpClient and get EmpData - All this performed on the server
Once you have EmpData you should have everything your need to return a NewEmp view.
In this particular case there is no need in AJAX at all. You can use regular form submit in case that you need to post some data or just a redirect to NewEmployee action.

mvc form collection issue

I am facing a weird problem. I have a cshtml form:
<label class="pre_req_questions_width">
#Html.RadioButton("radioGroup" + Model.ID, "1", (Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnYes", style = "margin-top:0px; margin-right:10px;" })Yes</label>
<label class="pre_req_questions_width">
#Html.RadioButton("radioGroup" + Model.ID, "2", !(Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnNo", style = "margin-top:0px;margin-right:10px;" })No</label>
On form submit, I am getting radio group value like this:
int radioValue = int.Parse(fc.GetValue(controlID).AttemptedValue);
It works fine when i call it from #Html.BeginForm(), but when i try to send form collection via ajax like this:
input = $(':input')
$.ajax({
type: "POST",
url: '#Url.Action("SavePrerequisiteQuestion", "Dashboard", new { id = #Model.ID })',
data: input,
dataType: "html",
success: function (msg) {
alert("fine");
}, error: function (req, status, error) {
// with error
alert(error);
}
});
It send both values like this "1,2" rather than sending just selected/submitted value.
In your ajax request, you're sending all :input elements as your data:
...
data: input
...
What you probably want is to just serialize your form data, and send it with the request:
...
data: input.closest('form').serialize()
...
This is assuming you have your radio buttons in a <form> tag.
It may not be so easy to work around this. For instance, to get a selected radio button, you can do this: jQuery get value of selected radio button
So you can't just take all inputs and get the values from them... instead, you have to have more of a selective approach, and handle different elements appropriately. Checkboxes and selects will also have a similar problem.
You can put the #Html.Beginform back in and hijack the form submit in your jQuery
$('#formID').on('submit', function(e){
e.preventDefault(); // Just to stop the automatic Non Ajax submission of the form
$.post($(this).attr('action'), $(this).serialize(), function (data) {
//do stuff on success callback
alert("fine");
});
});
You can inherit the action path from the Html.BeginForm itself in the path below by doing
$(this).attr('action')
Note: If you want to manually put the path in there you still can instead of getting it
from the form
Then use $(this).serialize() to just serialize the whole form like the person above me
suggested

Categories