1.将patial view转成字符串

     protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action"); ViewData.Model = model; using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw); return sw.GetStringBuilder().ToString();
}
}

然而并卵用,因为完全可以返回一个 partial view

publicActionResult
GetView()

{...

return
View("viewName",model);

}



2.页面跳转

return
RedirectToAction("Action","Controller2");

return
View("ViewName");



return Index(hm);



http://stackoverflow.com/questions/11955161/view-doesnt-refresh-after-redirecttoaction-is-done



Onsuccess(function(retURL){ windows.location(retURL);})

replace windows.location(retURL) with
location.replace(retURL)

public ActionResult AddData(CandidateViewModel viewModel)
{
var newCandidateId = 0;
newCandidateId = this._serviceClient.AddCandidate(viewModel);
stirng ReturnURL = "/DisplayCandidate/"+newCandidateId;
return JSON(ReturnURL);
}

3.ModelState



ModelState["test"].Errors.Count()



View:

@Html.ValidationMessageFor(m=>m.Name)

@Html.ValidationSummary()

Model:

[Required(ErrorMessage = "Please choose the Asset Group Path.")]

[DisplayName("Name :")]

[Remote("CheckName", "Student", HttpMethod = "POST", AdditionalFields = "Id", ErrorMessage = "Student Name already exists.")]

public string Name { get; set; }

Controller:

if (ModelState.IsValid)

{}

else

{

 ModelState.AddModelError("Name", "Error Message");

}          



4.Client IP

Request.UserHostName 

Request.UserHostAddress

HttpContext.Current.User.Identity.Name

//Get IP address
string ipStr = string.Empty;
if ( String.IsNullOrEmpty(ipStr) || ipStr == "127.0.0.1" || ipStr == "::1")
{
IPAddress[] arrIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
//Request.ServerVariables["remote_addr"] Dns.GetHostName()
foreach (IPAddress ip in arrIPAddresses)
{
if (ip.AddressFamily.Equals(AddressFamily.InterNetwork)) ipStr=ip.ToString();
}
Session["Remote_Addr1"] = Request.ServerVariables["Remote_Addr"];
Session["Remote_Addr2"] = Request.UserHostAddress;
Session["Remote_Addr3"] = ipStr;}

5.string to byte[],char[]

byte[] data2 = Encoding.Unicode.GetBytes(name);

char[] values = name.ToCharArray();



6.params

        public static void LogServiceError(Exception ex, string methodName, params object[] objs)
{
try
{
Dictionary<string, string> dics = LogFormatHelper.GetLogInfo(methodName);
LogServiceError(ex, dics,objs);
}
catch (Exception innerExp)
{
innerExp.Data.Add("Logger error", innerExp.Message);
AppLogger.LogError(innerExp);
}
}

7.SqlCommand 在transaction裏面

ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction.  The Transaction property of the command has not been initialized.

using (SqlTransaction tx = destinationConnection.BeginTransaction(IsolationLevel.RepeatableRead))

                {

                    try

                    {

                        SqlCommand sqlCmd = new SqlCommand("truncate table Info", destinationConnection);

                        sqlCmd.ExecuteNonQuery();

                        。。。

 需要改成                      

SqlCommand sqlCmd = new SqlCommand("truncate table Info", destinationConnection,tx);

sqlCmd.ExecuteNonQuery();

http://stackoverflow.com/questions/13677812/error-when-using-transaction

8.SqlBulkCopy - Unexpected existing transaction

http://stackoverflow.com/questions/19117106/sqlbulkcopy-unexpected-existing-transaction

using (SqlTransaction tx = destinationConnection.BeginTransaction(IsolationLevel.RepeatableRead))

                {

                    try

                    {

                        SqlCommand sqlCmd = new SqlCommand("truncate table Info", destinationConnection,tx);

                        sqlCmd.ExecuteNonQuery();

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))

                        {

                            bulkCopy.DestinationTableName = "Info";

                            bulkCopy.ColumnMappings.Add("COL1", "COL1");

                            ...

需要改成

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection,SqlBulkCopyOptions.Default,tx))

                        {

                            bulkCopy.DestinationTableName = "Info";

using (SqlConnection destinationConnection = new SqlConnection("..."))

            {

                destinationConnection.Open();

                using (SqlTransaction tx = destinationConnection.BeginTransaction(IsolationLevel.RepeatableRead))

                {

                    try

                    {

                        SqlCommand sqlCmd = new SqlCommand("truncate table Info", destinationConnection,tx);

                        sqlCmd.ExecuteNonQuery();

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection,SqlBulkCopyOptions.Default,tx))

                        {

                            bulkCopy.DestinationTableName = "Info";

                            bulkCopy.ColumnMappings.Add("COL1", "COL1");

...

bulkCopy.WriteToServer(dt);

                        }

                        tx.Commit();

                    }

                    catch (Exception ex)

                    {

                        tx.Rollback();

                        Console.WriteLine(ex.Message);

                        AppLogger.LogError(ex);

                    }

                    finally

                    {

                        tx.Dispose();

                    }

                }

            }

db.Connection.Open();

using
(db.Transaction = db.Connection.BeginTransaction())

{

try

{...

db.SubmitChanges();

db.Transaction.Commit();

}

catch
(Exception
ex)

{

db.Transaction.Rollback();

throw
ex;

}

finally

{

db.Connection.Close();

}

9.DbHelper

public static DataSet GetDataFromCommand(string cmdText, string connectionString)
{
using (OleDbConnection connDbConnection = new OleDbConnection())
{
connDbConnection.ConnectionString = connectionString;
connDbConnection.Open();
OleDbCommand objCommand = new OleDbCommand();
objCommand.CommandText = cmdText;
objCommand.Connection = connDbConnection;
DataSet ds = new DataSet();
OleDbDataAdapter objAdaptor = new OleDbDataAdapter();
objAdaptor.SelectCommand = objCommand;
objAdaptor.Fill(ds);
connDbConnection.Close();
connDbConnection.Dispose();
return ds;
}
}

10.StringHelper

        public static string ToTitleCase(object obj)
{
if (obj == null)
return string.Empty; string result = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Convert.ToString(obj).ToLower());
result = System.Text.RegularExpressions.Regex.Replace(result, @"\w+\&\w+", m => m.ToString().ToUpper());
return result;
}

11.链接

<ahref="javascript:(javascript:(void(0)))">Save</a>

12.AppDomain.CurrentDomain.BaseDirectory

string tempFolder = AppDomain.CurrentDomain.BaseDirectory + @"Temp\";

if (Directory.Exists(tempFolder)) Directory.Delete(tempFolder, true);

//string[] files = Directory.GetFiles(tempFolder, ".PDF");

//foreach (string file in files)

//{

//    System.IO.File.Delete(file);

//}



13.ReflectionHelper

public static void CopyObject(object target, object source, params string[] excludedProperties) {
if (source == null || target == null)
{
throw new ArgumentNullException("source/target object");
}
PropertyInfo[] props = source.GetType().GetProperties();
foreach (PropertyInfo p in props) {
if (excludedProperties != null && excludedProperties.Contains(p.Name)) {
continue; //ignore the property if exists in the specified excluded properties
}
if (p.CanRead && p.PropertyType.Namespace == "System") {
PropertyInfo targetProperty = target.GetType().GetProperty(p.Name);
if (targetProperty != null && p.PropertyType == targetProperty.PropertyType && targetProperty.CanWrite
&& !AreEqual(p.GetValue(source, null), targetProperty.GetValue(target, null))){
targetProperty.SetValue(target, p.GetValue(source, null), null);
}
}
}
}

14.EncryptionHelper

        public static string SHA1EncryptString(string sourceString) {
byte[] bytes = Encoding.UTF8.GetBytes(sourceString);
SHA1 sha = new SHA1CryptoServiceProvider();
string encryptedString = Convert.ToBase64String(sha.ComputeHash(bytes));
return encryptedString;
}

15.Validate

publicclassHomeModel:IValidatableObject

{

...

publicIEnumerable<ValidationResult>
Validate(ValidationContext
validationContext)

{

if
(...)

{

yieldreturnnewValidationResult(DisplayMsgs.Error);

}

}

}

16.引用传参数

public void Sort(ref int x,ref int y,ref int z)
{
   ...//里面代码不用变
}



Myclass m = new Myclass();
int a,b,c;
a = 10;b=20;c=10;
m.Sort(ref a,ref b,ref c);
....

MVC的一些有用代码的更多相关文章

  1. Mvc分页组件MvcSimplePager代码重构

    1 Mvc分页组件MvcSimplePager代码重构 1.1 Intro 1.2 MvcSimplePager 代码优化 1.3 MvcSimplePager 使用 1.4 End Mvc分页组件M ...

  2. Mvc分页组件MvcSimplePager代码重构及使用

    1 Mvc分页组件MvcSimplePager代码重构 1.1 Intro 1.2 MvcSimplePager 代码优化 1.3 MvcSimplePager 使用 1.4 End Mvc分页组件M ...

  3. 整理c# 不常用但有用代码

    # 整理c# 不常用但有用代码 1.winform窗体右键菜单打开其他窗体 private void contextMenuStripHandler_Click(object sender, Even ...

  4. Asp.net MVC 视图之公用代码

    一.公共模板 转自:http://www.cnblogs.com/kissdodog/archive/2013/01/07/2848881.html 1.@RenderBody() 在网站公用部分通过 ...

  5. 基于AOP的MVC拦截异常让代码更优美

    与asp.net 打交道很多年,如今天微软的优秀框架越来越多,其中微软在基于mvc的思想架构,也推出了自己的一套asp.net mvc 框架,如果你亲身体验过它,会情不自禁的说‘漂亮’.回过头来,‘漂 ...

  6. 用好spring mvc validator可以简化代码

    表单的数据检验对一个程序来讲非常重要,因为对于客户端的数据不能完全信任,常规的检验类型有: 参数为空,根据不同的业务规定要求表单项是必填项 参数值的有效性,比如产品的价格,一定不能是负数 多个表单项组 ...

  7. ASP.NET MVC+EF5 开发常用代码

      Asp.Net Mvc,EF 技术常用点总结 1.Asp.Net MVC a)获得当前控制器名和当前操作的名称(action) 1.Action 中 RouteData.Values[" ...

  8. MVC 数据验证收集代码

    控制器 Home using System; using System.Collections.Generic; using System.Linq; using System.Web; using ...

  9. ASP.NET MVC项目中EntityFramework"代码优先方法"的使用步骤

    EF提供了三种方式来实现项目,分别是: (1)代码优先方法: (2)模型优先方法: (3)数据库优先方法: 本篇主要记录在Vs2010环境下使用代码优先的方式实现数据库和后端代码数据交互,语言为C#, ...

随机推荐

  1. 20191011-构建我们公司自己的自动化接口测试框架-Util的TestDataHandler模块

    TestDataHandler模块主要是做测试数据的处理,包括转换数据格式和变量参数处理转换数据格式函数: data是数据,data以$()的方式识别变量,如果请求的数据有变量,则将变量用global ...

  2. Spring (1)框架

    Spring第一天笔记   1. 说在前面 怎样的架构的程序,我们认为是一个优秀的架构? 我们考虑的标准:可维护性好,可扩展性好,性能. 什么叫可扩展性好? 答:就是可以做到,不断的增加代码,但是可以 ...

  3. ActiveMQ 消息存储持久化

    ActiveMQ提供了一个插件式的消息存储,类似于消息的多点传播,主要实现了如下几种: AMQ消息存储-基于文件的存储方式,是以前的默认消息存储 KahaDB消息存储-提供了容量的提升和恢复能力,是现 ...

  4. AtCoder Grand Contest 040 B - Two Contests

    传送门 一看就感觉很贪心 考虑左端点最右的区间 $p$ 和右端点最左的区间 $q$ 如果 $p,q$ 属于同一个集合(设为 $S$,另一个集合设为 $T$),那么其他的区间不管是不是在 $S$ 都不会 ...

  5. (五)CXF之添加拦截器

    一.需求分析 webService中的拦截器类似于servlet的Filter过滤器.一般用于调用服务前后先调用拦截器的方法. 二.案例 本章案例是基于上一章节的基础上添加拦截器的 2.1 服务端添加 ...

  6. 取代Ajax.BeginForm的ajax使用方法

    原文:取代Ajax.BeginForm的ajax使用方法 一.前提概要 Asp.net core中已经取消了Ajax.BeginForm,也不会计划出ajax tag helper,所以得利用插件jq ...

  7. c#基础知识梳理(二)

    上期回顾 - https://www.cnblogs.com/liu-jinxin/p/10818256.html 一.变量 一个变量只不过是一个供程序操作的存储区的名字.在 C# 中,每个变量都有一 ...

  8. insert buffer/change buffer double write buffer,双写 adaptive hash index(AHI) innodb的crash recovery innodb重要参数 innodb监控

    https://yq.aliyun.com/articles/41000 http://blog.itpub.net/22664653/viewspace-1163838/ http://www.cn ...

  9. 【异常】airflow-psutil/_psutil_common.c:9:20: fatal error: Python.h: No such file or directory

    1 异常信息 usr/include/python3.6m -c psutil/_psutil_common.c -o build/temp.linux-x86_64-3.6/psutil/_psut ...

  10. Scyther-Semantics and verification of Security Protocol 翻译 (第二章 2.2.2----2.3)

    2.2.2  事件顺序 协议中的每个角色对应于事件列表,换句话说, 在属于角色 R 的协议事件集上施加结构,总的排序表示为 $ \prec $ , 如此任何角色 R∈Role 和 $\varepsil ...