I'm trying to call a method from view, but it's not working! :(
My Controller code:
public class ProfessionalController : Controller
{
//
// GET: /Professional/
public ActionResult Index()
{
return View();
}
public ActionResult Sum(int nro1, int nro2)
{
var value = nro1 + nro2;
ViewBag.SumResult = value;
return View();
}
}
My views code:
Professional Index:
@{
ViewBag.Title = "Profissional";
}
<h2>Profissional</h2>
@using (Html.BeginForm("Professional", "Sum")) {
<input id="nro1" type="number" class="form-control marged_top" placeholder="Numero 1" />
<input id="nro2" type="number" class="form-control marged_top" placeholder="Numero 2" />
<button id="Sum" name="Sum" value="Sum" class="btn btn-default" type="button"
data-toggle="button">
Sum
</button>
}
Sum View:
@{
ViewBag.Title = "Sum";
}
<h2>Sum</h2>
@ViewBag.SumResult;
Doesn't occurs any error, just nothing happens when i click at Sum button.
Some issues:
<button>
with type="submit"
, otherwise the form will not be submitted, and the button will do nothing. See also: MDN - Button Type Html.BeginForm("Professional", "Sum")
should be Html.BeginForm("Sum", "Professional")
- The controller is the second argument.Html.BeginForm("Sum")
would also work here, because this is the current controller.name="nro1"
, not id
- it is the name that is being submitted.@ViewBag.SumResult
(though that isn't a bug).data-toggle="button"
is doing here.Note that you are not "calling a Controller from a View" - you are submitting a form, which starts a new Controller-View cycle. Html.Action
can do something similar, but that is not what you're trying to do here.
I'd also take this opportunity and recommend against using ViewBag
- Use a strongly typed view model instead