ASP.NET C#-选择下拉列表未选择正确的值
我正在使用ASP.NETMVC编写一个基本应用程序。我有一个选择下拉列表,有三个文本值,空白,“是的,我会在那里”,“不,我不能来”。我希望在提交表单中的“是的,我会在那里”选项时,GuestResponse对象在控制器中注册选项值'true',但目前它只是作为“null”出现。我是否正确设置了表单,在模型中使用布尔类型是否合理 GuestResponse.cs(型号) RSVPForm.cshtmlASP.NET C#-选择下拉列表未选择正确的值,c#,asp.net-mvc,C#,Asp.net Mvc,我正在使用ASP.NETMVC编写一个基本应用程序。我有一个选择下拉列表,有三个文本值,空白,“是的,我会在那里”,“不,我不能来”。我希望在提交表单中的“是的,我会在那里”选项时,GuestResponse对象在控制器中注册选项值'true',但目前它只是作为“null”出现。我是否正确设置了表单,在模型中使用布尔类型是否合理 GuestResponse.cs(型号) RSVPForm.cshtml <form method="post" action=&qu
<form method="post" action="/Home/RsvpForm">
<div class="form-group">
<p>
<label for="Name">Your name:</label>
<input type="text" id="name" name="name" />
</p>
</div>
<p>
<label for="Email">Your email:</label>
<input type="text" id="email" name="email" />
</p>
<p>
<label for="Phone">Your phone:</label>
<input type="text" id="phone" name="phone" />
</p>
<p>
<label>
Will you attend?
</label>
<select asp-for="WillAttend">
<option value="Choose an option"></option>
<option value="true">Yes, I'll be there</option>
<option value="false">No, I can't come</option>
</select>
</p>
<button type="submit">Submit RSVP</button>
</form>
谢谢.cshtml(感谢页面)
@{
布局=空;
}
谢谢
谢谢,@Model.Name!
@如果(Model.willAttention==true){
@字体你能来真好。饮料已经在冰箱里了!
}否则{
@字体很抱歉听到你不能来了,但是谢谢你让我们知道。
}
单击@Html.ActionLink(“此处”、“列表响应”)查看谁来了
谢谢
问候,
罗伯特
英国伦敦您还可以使用name属性向控制器发送值
<select name="WillAttend">
<option value="Choose an option"></option>
<option value="true">Yes, I'll be there</option>
<option value="false">No, I can't come</option>
</select>
是的,我会去的
不,我不能来
value=“选择选项”不是bool。可能在选项中选择一个选项,并将值设置为True、False
public class HomeController : Controller
{
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse)
{
Repository.AddResponse(guestResponse); // "WillAttend" should return true here.
return View("Thanks", guestResponse);
}
public ViewResult ListResponses()
{
return View(Repository.Responses.Where(r => r.WillAttend == true));
}
}
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Thanks</title>
</head>
<body>
<p>
<h1>Thank you, @Model.Name!</h1>
@if (Model.WillAttend == true) {
@:It's great that you're coming. The drinks are already in the fridge!
} else {
@:Sorry to hear that you can't make it, but thanks for letting us know.
}
</p>
<p>Click @Html.ActionLink("here", "ListResponses") to see who is coming. </p>
</body>
</html>
<select name="WillAttend">
<option value="Choose an option"></option>
<option value="true">Yes, I'll be there</option>
<option value="false">No, I can't come</option>
</select>