dor dor - 1 month ago 17
C# Question

httppost dont work. mvc6 , c#

I am low mvc6 and c# skills, I am trying to post, when I sumbit it's doing nothing.

It wont take me to the controller, just stays on the page.

I have more pages, I dont know where is the problem, I will add the rest if need

Here my Controller:

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApplication1.ViewModels;

namespace WebApplication1.Controllers.Web
{
public class AppController : Controller
{
public IActionResult Index()
{
return View();
}

public IActionResult Contact()
{

return View();
}

[HttpPost]
public IActionResult Contact(ContactViewModel model)
{
return View();
}

public IActionResult About()
{
return View();
}
}
}


here my Contact:

@model WebApplication1.ViewModels.ContactViewModel

@{
ViewBag.Title = "Contact Page";
}

@section scripts{
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation- unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}
<h2>Contact Me</h2>

<form method="post">

<span asp-validtaion-summary="ModelOnly"></span>

<label asp-for="Name"></label>
<input asp-for="Name"/>
<span asp-validation-for="Name"></span>

<label asp-for="Email"></label>
<input type="email" asp-for="Email"/>
<span asp-validation-for="Email"></span>

<label asp-for="Message"></label>
<textarea cols="40" rows="4" asp-for="Message"></textarea>
<span asp-validation-for="Message"></span>

<div>
<input type="submit" value="Send Message" />
</div>

</form>

Answer

You forgot to tell the "form" what to do, when the user submits it. For MVC6 you can use this tag helper:

<form asp-controller="App" asp-action="Contact">
    ...
</form>

This will output something like

<form action="/App/Contact" method="post">

And now the Browser knows the action url and where to send to data.