Der Dropdown-Listenwert ist nach der Veröffentlichung auf dem Controller in ASP.NET MVC null
Posted: 03 Jan 2025, 08:09
Ich bin neu bei ASP.NET MVC. Ich habe ein einfaches Formular mit einer Schaltfläche zum Senden und einem HTML-Auswahlelement, das mit zwei Elementen gefüllt ist. Wenn das Formular an meinen Controller gesendet wird, sind alle Formularwerte null. Ich habe es stattdessen sogar mit $.POST versucht und die ID-Variable, die ich sende, ist null, wenn sie den Controller erreicht. Hier ist mein Code:
HTML
MVC-Controller
Es scheint, dass nichts im Formular gesendet wird. Ich habe auch Folgendes versucht:
JS
MVC-Controller für JS-Methode
Was mache ich falsch?
HTML
Code: Select all
@using (Html.BeginForm("SetOptionForUser", "MyController", FormMethod.Post, new { @class="form-inline" }))
{
@Html.AntiForgeryToken()
@foreach (var item in Model.Persons)
{
@item.Name
}
Go
}
Code: Select all
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult SetOptionForUser(FormCollection form)
{
string option = form["ddlSelect"].ToString(); //null error
return RedirectToAction("AnotherAction", "AnotherController");
}
JS
Code: Select all
$("#btnEnter").click(function (e) {
var optionId = $("#ddlSelect").val(); //this get val correctly
$.post(@Url.Action("SetOptionForUser", "MyController"), optionId);
});
Code: Select all
**MVC Controller**
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult SetOptionForUser(int optionId) //null
{
string option = optionId.ToString(); //null error
return RedirectToAction("AnotherAction", "AnotherController");
}