ASP.Net MVC: Calling a method from a view
This is how you call an instance method on the Controller:
@{
((HomeController)this.ViewContext.Controller).Method1();
}
This is how you call a static method in any class
@{
SomeClass.Method();
}
This will work assuming the method is public and visible to the view.
Simplest way to call a controller method from a view button in .Net (mvc)
You can use set href
path to call your controller
from view
.
<a class="btn btn-success" href="@Url.Action("Start", "DefaultController")">Start</a>
and if want to pass parameter then:
<a class="btn btn-success" href="@Url.Action("Start","DefaultController", new {id=Item.id })">Start</a>
or for other options you can check this link
you can call your controller method using ajax
also refer this link
AsP.Net MVC 5 how to call a function in view
You can call your server method by using the overload of Html.Action()
that accepts the action name as the first parameter and the route values as the 2nd parameter
@foreach(var r in user.Roles)
{
<p>@Html.Action("GetRoleNameById", new { roleId = r.RoleId })</p>
}
Pass a variable from a view to a controller action method and then to another method in the same ASP.NET MVC controller
You can use ViewData
or TempData
to persist your variables from one Controller action to another:
public JsonResult GetTokenFromView(string Token)
{
ViewData["PassedToken"] = Token;
return Json(Token);
// I have tried redirectToAction as well but the value becomes null.
}
And access it in your Thankyou
method like this:
public ActionResult Thankyou(string slug, string Token, string email)
{
slug = "thank-you";
Console.Write(Token);
//Token = ViewBag.PassedToken;
//Get your ViewData variables here
if (ViewData["PassedToken"] != null)
{
Token=ViewData["PassedToken"];
}
var savedToken = Token;
Console.Write(savedToken);
var url = "https://application.ecomapi.com/api/purchases/" + savedToken;
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
return View();
}
Related Topics
How to Spawn Threads on Different CPU Cores
Sharing Violation Ioexception While Reading and Writing to File C#
How to Convert a Character in to Equivalent System.Windows.Input.Key Enum Value
How to Set Web.Config File to Show Full Error Message
How to Remove an Xml Element from File
How to Avoid Multiple Instances of Windows Form in C#
Could Not Find Installable Isam
Limit the Number of Parallel Threads in C#
Custom JSON Serialization for Each Item in Ienumerable
Getmanifestresourcestream Returns Null
Explicit Conversion Operator Error When Converting Generic Lists
What's the Difference Between Using the Serializable Attribute & Implementing Iserializable
Serializing/Deserializing with Memory Stream
Determine Label Size Based Upon Amount of Text and Font Size in Winforms/C#
Securing a Password in Source Code