ASP.NET MVC - How to call void controller method without leaving the view?
Basically @Html.ActionLink()
or <a></a>
tag uses get request to locate the page. Hence whenever you clicked it, you request to your AddToCart action method in ProductController and if that action method returns null or void so a blank or empty page is shown as you experienced (because or @Html.ActionLink() get request by Default).
So if you want to add your value to cart then call AddToCart method using ajax i.e:
HTML:
@Html.ActionLink("Add To Cart", "AddToCart", null, new { id="myLink"})
Jquery or Javascript:
$("#myLink").click(function(e){
e.preventDefault();
$.ajax({
url:$(this).attr("href"), // comma here instead of semicolon
success: function(){
alert("Value Added"); // or any other indication if you want to show
}
});
});
'AddToCart' method in the ProductController:
public void AddToCart()
{
//Logic to add item to the cart.
}
Now this time when the call goes to AddToCart method it goes by using ajax hence the whole page will not redirect or change, but its an asynchronous call which execute the AddToCart action method in your ProductController and the current page will remains same. Hence the product will also added to cart and page will not change to blank.
Hope this helps.
ASP.NET MVC - How to call controller method and don't leave the view
You want to use Ajax.ActionLink instead of Html.ActionLink. The article below should specify some of the details of the usage. Make sure you remember to include the jquery libraries or it will not generate the link type you are expecting.
https://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/ajax-actionlink-and-html-actionlink-in-mvc/
Personally, I would not use the Microsoft method and write a jQuery Ajax postback myself in JavaScript.
Call a method without loading a view in MVC
You could use AJAX:
<td>
@Ajax.ActionLink(
"Delete",
"PutInBin",
"Capture",
new {
captureId = Model.Files.Captures.ElementAt(i).Capture_Id
},
new AjaxOptions {
HttpMethod = "POST",
}
)
</td>
and don't forget to include the jquery.unobtrusive-ajax.js
script to your page:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
and your controller action:
[HttpPost]
public ActionResult PutInBin(int captureId)
{
QueryCaptureToBin queryCaptureToBin = new QueryCaptureToBin();
queryCaptureToBin.Capture_Id = captureId;
client.PlaceCaptureInBin(queryCaptureToBin, userParams);
return new EmptyResult();
}
and if you wanted to get notification when the delete finishes:
<td>
@Ajax.ActionLink(
"Delete",
"PutInBin",
"Capture",
new {
captureId = Model.Files.Captures.ElementAt(i).Capture_Id
},
new AjaxOptions {
HttpMethod = "POST",
OnSuccess = "onDeleteSuccess"
}
)
</td>
and then you would have your onDeleteSuccess
javascript function:
var onDeleteSuccess = function(result) {
// normally the result variable will contain the response
// from the server but in this case since we returned an EmptyResult
// don't expect to find anything useful in it.
alert('The capture was successfully deleted');
};
How to call action method without view
If you want do to some work based off a button/link, why not just use an ajax call?
For example:
<div class="col-lg-6 col-md-8 col-sm-10 ">
<button onclick=GeneratePdf('@Model.DesignId', <string data>) class="btn btn-primary enabled"><i class="fa fa-fw fa-check"></i> @Resources.Action.Navigation.GeneratePDF </button>
</div>
And in your .cshtml, I would recommend having a Script section at the bottom of the file:
@section Scripts{
<script type="text/javascript">
//modify as needed to make it pass in what you need.
function GeneratePdf(designId, stringData) {
$.ajax({
url: "@Url.Action("GeneratePDFFFromHtml","Product")",
data: { designId: designId, strData: stringData },
cache: false,
contentType: false,
processData: false,
type: "POST",
success: function (data) {
//TODO: Add whatever if you want to pass a notification back
},
error: function(error) {
//TODO: Add some code here for error handling or notifications
}
}
</script>
}
Then, in your controller, you can have your function return void. NOTE: I am not really sure if you even need to pass in the DesignId but you have it in there so I will keep it there. You will most-likely need to edit this method some more to make it work properly but hopefully this will get you going.
[HttpPost]
public void GeneratePDFFFromHtml(string designId, string strData)
{
SubmittedForm sf = new SubmittedForm();
string schema = requestSchema;
customer_DbConnection db = new customer_DbConnection();
RenderFormController renderController = new RenderFormController();
renderController.GeneratePdf(strData, db, sf);
//return RedirectToAction(model.DesignId, "Prdocut/Edit");
}
Also, this will be async so you may want some notification to the user that some action is being done like a spinner.
Call void function inside of controller
Change method name;
public void deleteFunc(int id)
EDIT
Firstly, you should be careful about naming convention. I change your class name like DeleteAction
and method name DeleteRecord
public class DeleteAction
{
public void DeleteRecord(int id)
{
//xxx
const string ConnStr = "...";
MySqlConnection connection = new MySqlConnection(ConnStr);
connection.Open();
MySqlCommand sqlcmd2;
sqlcmd2 = connection.CreateCommand();
sqlcmd2.CommandText = "UPDATE `user` SET Aktive = 0 WHERE Nr = @id;";
sqlcmd2.Parameters.Add("@id", MySqlDbType.Int32).Value = id;
sqlcmd2.ExecuteNonQuery();
connection.Close();
//xxx
}
}
Then, you can call desired function by creating an instance from class;
public ActionResult delete(int id)
{
var deleteActionObject = new DeleteAction();
deleteActionObject.DeleteRecord(id);
return RedirectToAction("Index");
}
Invoking a controller's action by button in View without redirecting to any view
Have you tried jQuery's $.get (http://api.jquery.com/jquery.get/) or $.post (http://api.jquery.com/jquery.post/). After including reference to jQuery, you can do something like this:
<button id='mybutton'>Click Me</button>
<script>
$('#mybutton').click(function(){
$.post( "mysite/UpdateDatabase", {personId: "@Model.Item1.Id", surveyId: "@survey.Id"}, function( data ) {
alert('updated');
});
});
</script>
Run MVC controller action without the view?
Make sure your action method does not return a ActionResult:
public void DoSomething()
How do I create a button that calls a method in a controller without changing views?
Try this:
View page code:<input type="button" id="yourBtn" value="Click Me!" />
Javascript:<script type="text/javascript">
$("#yourBtn").click(function(){
var id = **YourIntValue**
$.ajax({
url: "@Url.Action("ButtonPrompt","Home")",
type: "GET",
data: { id: id },
dataType: 'json',
cache: false,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error" + errorThrown)
},
success: function(data){
//Do nothing
}
});
});
Controller:public ActionResult ButtonPrompt(int? id)
{
.. your code ....
return Json(true);
}
How to call void functions from view .Net Core
I made a simple example, you can refer to it.
View (Messagelookup.cshtml):
@{
ViewData["Title"] = "Messagelookup";
}
<h1>Messagelookup</h1>
<div>
<label>MessageId:</label>
<h2>@ViewBag.MessageId</h2>
</div>
<a class="btn btn-info mt-3" asp-controller="MessageCenter" asp-action="Markmessage" asp-route-messageid="2">Mark</a>
Controller:
public class MessageCenterController : Controller
{
public IActionResult Messagelookup(int? Messageid)
{
ViewBag.Messageid = Messageid;
return View();
}
public IActionResult Markmessage(int? messageid)
{
return RedirectToAction("Messagelookup", new { Messageid = messageid });
}
}
Result:
Related Topics
Declare Properties to Ignore in Entities Interface (Ef Core)
How to Use a Class from One C# Project With Another C# Project
Validate Indian Phone Number With Optional +91 or 0 Preceeding 10 Digits
What Could Cause an Assignment to Not Work
Fastest Way to Find Strings in a File
How to Asynchronously Wait for X Seconds and Execute Something Then
Launch an Application and Send It to Second Monitor
Adding an Incremental Number to Duplicate String
Using Linq to Remove Elements from a List<T>
Check If Datetime Is a Weekend or a Weekday
Empty String Not Being Converted to Null When Passing Json Object to Controller
Unexpected Character Encountered While Parsing Value
Restsharp Serializing Json Objects to Post Parameters
Asp.Net Core Form Post Results in a Http 415 Unsupported Media Type Response
How to Set Datetimepicker to Month and Year Only Format
C# How to Simply Encrypt a Text File With a Pgp Public Key