ASP.NET MVC: Calling a Method from a View

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



Leave a reply



Submit