警告框在asp.net mvc中应用

Bootstrap与asp.net MVC框架结合,产生警告框。主要是利用控制器的TempData 字典对象 生成临时数据。

ASP.NET MVC的TempData用于传输一些临时的数据,例如在各个控制器Action间传递临时的数据或者给View传递一些临时的数据,相信大家都看过“在ASP.NET页面间传值的方法有哪几种”这个面试题,在ASP.NET MVC中TempData的就是其中的一种传值方法。TempData默认是使用Session来存储临时数据的,TempData中存放的数据只一次访问中有效,一次访问完后就会删除了的。这个一次访问指的是一个请求到下一个请求,因为在下一个请求到来之后,会从Session中取出保存在里面的TempData数据并赋值给TempData,然后将数据从Session中删除。也就是说TempData只保存到下一个请求中,下一个请求完了之后,TempData就会被删除了。注意这里TempData使用Session来做存储的,Session是对应特定用户的,所以并不存在并发问题。

1、定义Alert 类

public class Alert
{
public const string TempDataKey = "TempDataAlerts";

public string AlertStyle { get; set; }
public string Message { get; set; }
public bool Dismissable { get; set; }



}

public static class AlertStyles
{
public const string Success = "success";
public const string Information = "info";
public const string Warning = "warning";
public const string Danger = "danger";
}

}

2、定义基控制器,BaseController,使它能够产生list<alert>类型的 TempData 对象。

public class BaseController : Controller
{
// GET: Base
public void Success(string message, bool dismissable = false)
{
AddAlert(AlertStyles.Success, message, dismissable);
}

public void Information(string message, bool dismissable = false)
{
AddAlert(AlertStyles.Information, message, dismissable);

}
public void Warning(string message, bool dismissable = false)
{
AddAlert(AlertStyles.Warning, message, dismissable);
}

public void Danger(string message, bool dismissable = false)
{
AddAlert(AlertStyles.Danger, message, dismissable);
}

private void AddAlert(string alertStyle, string message, bool dismissable)
{
var alerts = TempData.ContainsKey(Alert.TempDataKey)
? (List<Alert>)TempData[Alert.TempDataKey]
: new List<Alert>();

alerts.Add(new Alert
{
AlertStyle = alertStyle,
Message = message,
Dismissable = dismissable
});

TempData[Alert.TempDataKey] = alerts;



}

}

3、要使用的控制器继承上面创建的基控制器。并在方法中添加生成 临时数据的代码。

public class PersonController :BaseController
{

[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
_people.Add(person);
Success(string.Format("<b>{0}</b>已经成功添加到数据库", person.FirstName), true);
return RedirectToAction("Index");
}
Danger("出错了,请检查你的表单");
return View(person);

}

4、添加_Alerts.csthml部分视图。并在布局页上包含部分视图。

_Alerts.csthml

@{
var alerts = TempData.ContainsKey(Alert.TempDataKey)
? ((List<Alert>)TempData[Alert.TempDataKey])
: new List<Alert>();

if (alerts.Any())
{
<hr />
}

foreach (var alert in alerts)
{
var dismissabelClass = alert.Dismissable ? "alert-dismissable" : null;
<div class="alert alert-@alert.AlertStyle @dismissabelClass">
@if(alert.Dismissable)
{
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
&times;
</button>
}

@Html.Raw(alert.Message);
</div>

}

}

_Layout.cshtml上包含部分视图

</div>
<div class="container body-content">
@{Html.RenderPartial("_Alerts");}
@RenderBody()

原文地址:https://www.cnblogs.com/liuyuanhao/p/4381437.html