網(wǎng)站首頁 編程語言 正文
在ASP.NET MVC4中,HtmlHelper為我們提供了Html.RadioButton()方法用來顯示Radio Button單選按鈕。如果想顯示一組單選按鈕,通常的做法是遍歷一個集合把每個單選按鈕顯示出來。本篇嘗試寫一個擴展方法用來展示一組帶驗證的單選按鈕。
首先來擴展HtmlHelper,擴展方法中接收一個SelectListItem的集合,遍歷這個集合把每個單選按鈕顯示出來,并且讓這些單選按鈕具有不同的id屬性值。
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc.Html;
namespace System.Web.Mvc
{
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> list)
{
//獲取元數(shù)據(jù)
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
if (list != null)
{
foreach (var item in list)
{
//把屬性名和集合元素的Value值拼接作為元素的id
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
//創(chuàng)建單選按鈕
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new {id = id}).ToHtmlString();
sb.AppendFormat("<div class=\"RadioButton\">{0}{1}</div>", radio, label);
}
}
return MvcHtmlString.Create(sb.ToString());
}
}
}
假設(shè),現(xiàn)在有一個View Model,其中的一個屬性要求必須。
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class Vm
{
[Required(ErrorMessage = "必填")]
public int CityId { get; set; }
}
}
以下City類的集合將作為所有Radio Button的數(shù)據(jù)源。
namespace MvcApplication1.Models
{
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
}
在HomeController中,提供一個Action方法啊,把City的集合轉(zhuǎn)換成SelectListItem集合傳遞給視圖。
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
List<City> cities = new List<City>()
{
new City(){Id = 1, Name = "青島"},
new City(){Id = 2, Name = "濟南"},
new City(){Id = 3, Name = "平度"}
};
ViewData["c"] = from c in cities
select new SelectListItem() {Text = c.Name, Value = c.Id.ToString()};
return View(new Vm());
}
[HttpPost]
public ActionResult Index(Vm vm)
{
if (ModelState.IsValid)
{
return Content(vm.CityId.ToString());
}
else
{
return View(vm);
}
}
}
}
在_Layout.csthml中,必須具備客戶端驗證js。
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
</head>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
在Home/Index.chtml中,使用擴展方法顯示Radio Button組。
@model MvcApplication1.Models.Vm
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<style type="text/css">
.RadioButton { float:left; }
</style>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new {id = "addForm"}))
{
@Html.RadioButtonListFor(v => v.CityId, ViewData["c"] as IEnumerable<SelectListItem>)
@Html.ValidationMessageFor(v => v.CityId)
<input type="submit" value="提交"/>
}
原文鏈接:https://www.cnblogs.com/darrenji/p/4199391.html
相關(guān)推薦
- 2022-05-13 windwos11 小愛音箱鏈接上但是沒有聲音
- 2022-11-09 LyScript實現(xiàn)Hook隱藏調(diào)試器的方法詳解_python
- 2022-02-07 virtualenvwrapper 解決安裝報錯,virtualenvwrapper 永久生效
- 2022-07-21 shardingjdbc+mybatisP+Seata 報錯 throw new ShouldNev
- 2022-07-09 docker 中進程的信號
- 2024-01-14 Spring boot 注解@Async不生效 無效 不起作用
- 2022-10-17 Go如何優(yōu)雅的使用字節(jié)池示例詳解_Golang
- 2022-04-11 C#實現(xiàn)簡單的計算器小程序_C#教程
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支