Gratte.Aurora.Data.Models.Entity.cs
Gratte.Aurora.Data.Models.DataModelQueries.cs
<% if (this.Page.User.hasWASPPSpermission("ENTITYPROTECTIONPLAN", "A")) {%>
this.Page.User.IsInRoles( SecurityGroups.Translators )
fnLib.userName() 返回 return HttpContext.Current.User.Identity.Name;
ViewModel:return this.ViewMode == ViewModelMode.Create ? "no_time" : this.Entity.ReportedOn.ToString("t", this.UserFormatCulture);
Entity的ViewModel中需要验证Address:
protected override void OnValidation()
{
base.OnValidation();
// Validate...
this.Entity.Address.Validate();
// ...and then store the errors in the view.
this.ValidationErrors.AddRange( this.Entity.Address.GetErrors() );
}
<%= this.Html.DropDownList("Entity.MasterRisks", this.Model.MasterRisks, false, null)%>
<%= this.Html.DropDownList("Entity.LossTypeID", this.Model.Categories, Gratte.Aurora.SHlib.labelText("All_UICaption_NoLossItemType"))%>
<%= this.Html.Button("Cancel", HtmlButtonType.Normal, Gratte.Aurora.SHlib.labelText("IR_Template_SaveButton_Cancel"), 84, null, new Dictionary<string, object>() { { "onclick", "GoToIndex();" } } )%>
<%= this.Html.ActionLink(Gratte.Aurora.SHlib.labelText("IR_IncidentTemplate_Details_Edit"), "Edit", new { id = this.Model.Entity.Id }, new { @class = "optionlink" })%>
<%= this.Html.TextArea( "Entity.Summary", this.Model.Entity.Summary, 4, 85, 3000, false, null ) %>
<%= this.Html.CheckBox( "Entity.SkuRequired", this.Model.Entity.SkuRequired, false, null )%>
<%= this.Html.TextBox("Entity.SupportingResourceOther", this.Model.Entity.SupportingResourceOther, 16, 85, false, null)%>
<%= this.Html.Hidden( "ContentLanguage", this.Model.ContentLanguage ) %>
<%= this.Ajax.ActionLink( Gratte.Aurora.SHlib.labelText("IR_RepOff_Index_Link_CreateOffender"), "Create", "ReportOffender",
new RouteValueDictionary() { { "reportId", this.Model.ReportId } },
new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "offender-edit-dialog", OnSuccess = "ShowOffenderEditDialog" },
new Dictionary<string, object>() { { "class", "optionlink" } } ) %>
<%=new Aurora.WebClient.Controllers.IncidentReporting.TemplateController().GetCheckStr(true)%>
事务:
using (TransactionScope transactionScope = new TransactionScope())
{
using (SysEntities db = new SysEntities())
{
repository.Delete(db, deleteCollection);
if (deleteCollection.Length == repository.Save(db))
{
transactionScope.Complete();
return true;
}
else
{
Transaction.Current.Rollback();
}
}
}
验证提示信息:
View:
<%=Html.ValidationSummary("") %>
Controller:
ModelState.AddModelError("Error", "您提交的信息还未通过审核!");
if ((!this.ModelState.IsValid)) return this.RedirectWithErrors(this.View(DeleteViewName, viewModel), viewModel.GetErrors());
$.ajax({
type : 'POST',
url : 'InsertRespond',
dataType : 'json',
data : param,
error :function(msg){
alertBox('提交失败',msg,'error');
return false;
},
success : function(msg){
$('#header h2').html('提交成功!');
$('#main').addClass('hide').next().removeClass('hide');
setT();
return false;
}
});
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetNotification(int id)
{
string content = "";
try
{
using (AuroraDataContext db = new AuroraDataContext())
{
var template = db.IncidentTemplates.SingleOrDefault(x => x.Id == id);
if (template != null)
{
content = template.Notification;
}
}
}
catch (Exception ex)
{
return Json(new { msg= ex.Message}, JsonRequestBehavior.AllowGet);
}
return Json(new { msg = content }, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AjaxValidateReportDate(int id, DateTime reportDate)
{
return this.Json(new { IsValid = IncidentReport.ValidateReportDate(reportDate) });
}
调用方法: context.GetRepository<IncidentReport>().FindForUser()
搜索:
<!-- GRID FILTER -->
<script language="javascript" type="text/javascript">
function AuroraPerformFilter() {
var filter = document.getElementById("FilterParameter");
if (filter != null && filter.value.length > 0) {
window.location.href = "/User/Filter?FilterParameter=" + filter.value;
}
}
</script>
<b><% = Gratte.Aurora.SHlib.labelText("User_Index_TableHeader_FilterUsers") %></b>
<% = this.Html.TextBox("FilterParameter", Request.QueryString["value"], new { maxlength = 20 } )%>
<a id="FilterLink" href="#" onclick="AuroraPerformFilter();" class="optionlink"><% = Gratte.Aurora.SHlib.labelText("User_Index_TableHeader_Filter") %></a>
<a id="ClearLink" href="/User" class="optionlink"><% = Gratte.Aurora.SHlib.labelText("User_Index_TableHeader_Clear") %></a>
Controller:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Filter(int? page, string FilterParameter)
{
using (AuroraDataContext context = new AuroraDataContext())
{
int pageSize = Properties.Settings.Default.PageListSize;
int pageNumber = !page.HasValue ? 0 : page.Value - 1;
// Retrieve list of users that our logged in user is allowed to see, get a distinct list of those, then join that with UserProfile
var relatedUserNames = context.udf_GetUserNameAndEntitiesAndGroupsFromUserName(this.fnLib.userName(), 9999, null, true);
var dNames = (from n in relatedUserNames select new { UserName = n.UserName }).Distinct();
IEnumerable<UserProfile> users = (from up in context.UserProfiles
join dn in dNames on up.UserName equals dn.UserName
where (FilterParameter != null && (up.UserName.Contains(FilterParameter) || up.Name.Contains(FilterParameter)))
select up);
return this.View(IndexViewName, new UserListViewModel(users.LoadWith(UserProfile.LoadOptions.All).ToPagedList(pageSize, pageNumber, null)));
}
}
除了用$("form").submit() 还能用 '/user?id=5' 地址栏传参.
window.location.href = "/Report/Delete/30239";
//路径为 '控制器/方法名'
$.post("/ReportAttachment/Create", { "func": "getNameAndTime" },function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
using (IUnitOfWork context = IocServiceFactory.Resolve<IUnitOfWork>())
context.GetRepository<IncidentReport>()
using (AuroraDataContext db = new AuroraDataContext())
先建SystemSetting.cs页面,再建SystemSettingsViewModel.cs 页面;
[Bind(Exclude = "Id")]
public static bool ValidateReportDate(DateTime value)
{
return DateTime.Now.Add( TimeSpan.FromDays( 1 ) ).Subtract( value ).Days <= 15;
}
dbml文件再次拖入后'表关系'和'生成的属性名称'可能会改变。
Request["name"] 取的是name的值;
包含在tab中的内容
$('#losses-ajax-panel').load('<%= this.Url.Action( "Index", "ReportLoss", new RouteValueDictionary() { { "reportId", this.Model.Entity.Id } } ) %>');
aspx页面ajax调用:
<%= this.Ajax.ActionLink( Gratte.Aurora.SHlib.labelText("IR_RepLoss_Index_Link_CreateLoss"), "Create", "ReportLoss",
new RouteValueDictionary() { { "reportId", this.Model.ReportId } },
new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "loss-edit-dialog", OnSuccess = "ShowLossEditDialog" },
new Dictionary<string, object>() { { "class", "optionlink" } } ) %>
<a class="datalistoptionlink" title="<%= Gratte.Aurora.SHlib.labelText("IR_Rep_Index_Link_Edit") %>" href="<%= this.Url.Action( "Edit","ReportAttachment", new { id = item.Id } ) %>">
<img class="datalistoption" alt="Edit" src="<%= this.Url.Content( "~/Content/Images/Edit_16x16.png" ) %>" />
</a>
MVC下载文件:
<a class="optionlink" href="/ReportAttachment/QueryDownLoadAttachment/<%=item.Id %>">DownLoad</a>
public void QueryDownLoadAttachment(int id)
{
using (IUnitOfWork context = IocServiceFactory.Resolve<IUnitOfWork>())
{
var info = context.GetRepository<IncidentAttachment>().FindById(id);
string serverPath = info.AttachmentURL;
Stream fs = new FileStream(serverPath, FileMode.Open, FileAccess.Read, FileShare.Read);
FileInfo fi = new FileInfo(serverPath);
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment;filename=" + fi.Name);
Response.ContentType = ContentType.MimeType(info.AttachmentName);
Response.WriteFile(serverPath);
}
}
男女:
this.Genders = new SelectList(new[] { new { Id = "Male", Text = SHlib.labelText("IncidentReport_Offender_Sex_Male") }, new { Id = "Female", Text = SHlib.labelText("IncidentReport_Offender_Sex_Female") } }, "Id", "Text", this.Entity.Sex);
方法写在*ViewModel.cs文件中;
Controller:
if( !viewModel.WeaponSelected )
model.WeaponId = null;
ViewModel:
this.WeaponSelected = entity.WeaponId.HasValue;
public bool WeaponSelected { get; set; }
Create方法中有参数:
public ActionResult Create(int reportId)
{
ReportOffenderViewModel viewModel = new ReportOffenderViewModel( ViewModelMode.Create );
viewModel.Entity.ReportId = reportId;
public ActionResult Create(int LossTypeID)
{
IncidentLossItemSubType obj = new IncidentLossItemSubType();
obj.LossTypeID = LossTypeID;
LossItemSubTypeViewModel viewModel = new LossItemSubTypeViewModel(obj,ViewModelMode.Create);
js验证数字方法:
function isDigit(s){
var patrn=/^[0-9]{1,20}$/;
if(!patrn.exec(s)) return false;
return true;
}
//验证整形和浮点型
if (isNaN($("#Entity_Compensation").val())) {
//非数字
}
字符串IndexOf 比数组的 Containt 效率高;
加菜单项在PermissionsAndDashboardSectionsAndItems.sql的3个5.4的地方;
//取得下拉框选取值的文本
$('#testSelect option:selected').text();或$("#testSelect").find('option:selected').text();
用户控件页面:
public ActionResult SearchRisk(int reportId, int entityId, int? page)
{
return this.PartialView(SearchRiskViewName, new ListViewModel<ProtectionRisk>(System.Web.HttpContext.Current, list));
}
update UserProfile set [LanguageId]='en-GB' where username ='wasppsadmin'
fnLib.userLanguage();
fnLib.userHasPermission( permission, "A" ) == false
ALTER TABLE incidenttemplate ADD IsShowHealthCheck bit NOT NULL default 1
linq将字符串返回数组集合:
IEnumerable<int> templateEntities = Enumerable.Empty<int>();
if (!string.IsNullOrEmpty(template.Entities))
{
templateEntities = from t in template.Entities.Split(',')
select SharedHelper.TryParseInt32(t) into x
where x.HasValue
select x.Value;
}
向字表Translation中插入数据
model.SaveLanguage(fnLib.userLanguage());
Linq to Sql 查询指定类型的对象
//var list = db.GetRisksByUsername(fnLib.userName(),fnLib.userLanguage()).Select(c => new RiskInfo { RiskId = c.LinkToMasterRiskIdFromTemplate, Name = c.Name });
var list = from x in db.GetRisksByUsername(fnLib.userName(), fnLib.userLanguage()) select new RiskInfo() { RiskId = c.LinkToMasterRiskIdFromTemplate, Name = c.Name };
sqlserver:
对于有主外键关系的表注意是否要指定Cascade属性。双击Keys下面的某个外键关系,‘INSERT And UPDATE Specifical’选择 'Cascade'
js中Ajax不能放在循环中;
DropDownList绑定内容:
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = masterName, Value = MasterRiskId.ToString() });
return new SelectList(items, "Value", "Text", MasterRiskId);
//注意Contains方法中字符串的大小写
students = students.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper()) || s.FirstMidName.ToUpper().Contains(searchString.ToUpper()));
$("tr:visible") ,查找所有可见的 tr 元素; $("tr:hidden") ,查找所有不可见的tr元素
数据处理中,请等待:
var docheight = $(document).height();
$("body").append("<div id='greybackground'></div>");
$("#greybackground").css({ "opacity": "0.5", "height": docheight });
$("<div id=maskDiv class=\"datagrid-mask\" style=\"display:block\"></div>").appendTo(_196);
$("<div id= maskmsgDiv class=\"datagrid-mask-msg\" style=\"display:block\">Processing, please wait ...</div>").appendTo(_196);
System.Threading.Thread.Sleep(500);
asp:
<asp:TemplateField Visible="false" HeaderText="BCDT_FileExists" HeaderStyle-CssClass="WFGridViewOptionsCol" >
<ItemTemplate>
<asp:Label id="LBFileExists" Visible="false" runat="server" Text='<%# Bind("FileExists") %>' />
</ItemTemplate>
</asp:TemplateField>
string resourceTypeId = ((Label)gr.Cells[9].FindControl("LBResourceTypeId")).Text;
前台页面尽量尽量少用Ajax;
aspx页面使用<asp:GridView:
protected void GVviewMasterChildren_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
//e.Row.Cells[8].Visible = true;
if (e.Row.RowType == DataControlRowType.DataRow)
{
string lang = DataBinder.Eval(e.Row.DataItem, "Language").ToString();//不用找隐藏控件,直接绑定已有的字段
HyperLink downloadHL = (HyperLink)e.Row.FindControl("HLdownload");
移除IE中点击链接时的虚线框:a { outline:0;}
Linq返回自增长id:
mfr.SaveLanguage(fnLib.userLanguage());
int failureReasonId = mfr.Id;
int controlId = 0;
if (Int32.TryParse(LBcontrolId.Text, out controlId) && controlId > 0)
{
}
Sql查询语句,在三个字段中查询关键字:
SELECT a.id,b.name as category,c.name
FROM dbo.ProtectionControlMitigatorMechanismFailureReason a,ProtectionControlMitigatorMechanismFailureReasonCategoryTranslation b,ProtectionControlMitigatorMechanismFailureReasonTranslation c
WHERE
(
a.ProtectionControlMitigatorMechanismFailureReasonCategoryId=b.id and a.id=c.id
and b.[language]=@language and c.[language]=@language and
(
((c.name LIKE '%' + @sParam + '%' AND ISNUMERIC(@sParam) = 0) OR LEN(@sParam) = 0)
OR
((b.name LIKE '%' + @sParam + '%' AND ISNUMERIC(@sParam) = 0) OR LEN(@sParam) = 0)
OR
(a.id = CASE WHEN ISNUMERIC(@sParam) = 1 THEN CAST(@sParam AS INTEGER) ELSE -1 END OR LEN(@sParam) = 0)
)
)
order by c.name,a.zorder
using (SqlCommand c = fnLib.getSqlCmd(fnLib.getSQL("UPSERT_ProtectionControlMitigatorToProtectionControlMitigatorMechanismFailureReason")))
{
c.Parameters.AddWithValue("@ProtectionControlMitigatorId", mitigatorId);
c.Parameters.AddWithValue("@ProtectionControlMitigatorMechanismFailureReasonId", Convert.ToInt32(DDFailureReasons.SelectedValue));
c.Parameters.AddWithValue("@zOrder", TBMitigatorFailureReasonzOrder.Text);
c.ExecuteNonQuery();
c.Connection.Close();
}
安装EntityFramework4.1.exe,添加引用EntityFramework.dll;
Membership的表可以建在已知数据库里面,创建一个新的基于Internet模板的MVC项目,拷贝web.config中的Membership等节点,使用ASP.NET Configuration页面配置,拷贝account页面等;
waspps.mdf附加报错“拒绝访问”,解决方法:右键 属性-安全-添加Users组,勾选完全控制
int? count;
return count ?? 0;
if(string.Equals(values["Product"],PromoCode,StringComparison.OrdinalIgnoreCase)==false) //比较连个字符串,不区分大小写
public string GetCartId(HttpContextBase context)
{
if (context.Session[CartSessionKey] == null)
{
//如果用户已经登陆,那么用户名就是购物车的标识
if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
{
context.Session[CartSessionKey] = context.User.Identity.Name;
}
else
{
// Generate a new random GUID using System.Guid class
Guid tempCartId = Guid.NewGuid();
// Send tempCartId back to client as a cookie
context.Session[CartSessionKey] = tempCartId.ToString();
}
}
return context.Session[CartSessionKey].ToString();
}
VS2008左上点击断开连接,然后还原数据库。
@Model int
System.Security.Principal.IPrincipal user=this.HttpContext.User;
if(System.Security.Principal.IPrincipal.Identity.IsAuthenticated)