创建表单
<form asp-controller="Account"
asp-action="Login"
asp-route-returnurl="@ViewData["ReturnUrl"]"
method="post" class="form-horizontal">
</form>
|
Input 输入框
type:
.NET type | Input Type |
Bool |
type=”checkbox” |
String |
type=”text” |
DateTime |
type=”datetime” |
Byte |
type=”number” |
Int |
type=”number” |
Single, Double |
type=”number” |
checkbox 多选
<input type="checkbox" asp-for="selected" />同意协议
定义为bool类型:public bool selected { get; set; }
|
textarea 多文本输入框
<textarea asp-for="Description"></textarea>
|
select 下拉选择
<select asp-for="Country" asp-items="Model.Countries"></select>
定义类Class:
public string Country { get; set; }
public List<SelectListItem> Countries { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "MX", Text = "Mexico" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "US", Text = "USA" },
};
控制函数Controller:
public IActionResult Index(FormModel model)
{
if (ModelState.IsValid)
{
var msg = model.Country + " selected";
return RedirectToAction("IndexSuccess", new { message = msg });
}
return View(model);
}
|
在定义类Country的时候定义为: public IEnumerable<string> Country { get; set; }即可设置为可多选的选项;
默认不想选择数组中的第一个,可以设置为“请选择”:
<select asp-for="Country" asp-items="Model.Countries">
<option value="">请选择</option>
</select>
|
Option Group
下拉选择分组选项:
public FormModel()
{
var NorthAmericaGroup = new SelectListGroup { Name = "North America" };
var EuropeGroup = new SelectListGroup { Name = "Europe" };
Countries = new List<SelectListItem>
{
new SelectListItem
{
Value = "MEX",
Text = "Mexico",
Group = NorthAmericaGroup
},
new SelectListItem
{
Value = "CAN",
Text = "Canada",
Group = NorthAmericaGroup
},
new SelectListItem
{
Value = "US",
Text = "USA",
Group = NorthAmericaGroup
},
new SelectListItem
{
Value = "FR",
Text = "France",
Group = EuropeGroup
},
new SelectListItem
{
Value = "ES",
Text = "Spain",
Group = EuropeGroup
},
new SelectListItem
{
Value = "DE",
Text = "Germany",
Group = EuropeGroup
}
};
}
public string Country { get; set; }
public List<SelectListItem> Countries { get; }
|