MVC的一些有用代码

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);
....

 

 

 

 

posted on 2015-07-26 21:14  白马酒凉  阅读(203)  评论(0编辑  收藏  举报

导航