Asp .Net MVC – Dinamik Tablo Oluşturma

@model IEnumerable<object>

@{
    string[] includTypes = new string[]
    {
        "System.Boolean",
        "System.Byte",
        "System.SByte",
        "System.Char",
        "System.Decimal",
        "System.Double",
        "System.Single",
        "System.Int32",
        "System.UInt32",
        "System.Int64",
        "System.UInt64",
        "System.Int16",
        "System.UInt16",
        "System.String"
    };
    var first = Model.FirstOrDefault();
    if (first != null)
    {
        var firstProps = first.GetType().GetProperties();
        string tableId = "table" + first.GetType().Name;

        <table id="@tableId"
               data-show-columns="true"
               no-records-found="false"
               data-pagination="true"
               data-search="true">
            <thead>
                <tr>
                    @foreach (var pInfo in firstProps)
                    {
                        if (pInfo != null && includTypes.Any(m => m == pInfo.PropertyType.FullName))
                        {
                            var translate = ContextResource.ResourceManager.GetString(pInfo.Name);
                            translate = string.IsNullOrWhiteSpace(translate) ? pInfo.Name : translate;
                            var visible = pInfo.Name.EndsWith("Id") ? "false" : "true";
                            <th data-field="@pInfo.Name" data-visible="@visible"> @translate</th>

                        }
                    }
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    var props = item.GetType().GetProperties();

                    <tr>
                        @foreach (var pInfo in props)
                        {
                            if (pInfo != null && includTypes.Any(m => m == pInfo.PropertyType.FullName))
                            {
                                var value = pInfo.GetValue(item, null);
                                if (value != null)
                                {
                                    <td>@value.ToString()</td>
                                }
                                else
                                {
                                    <td>-</td>
                                }

                            }
                        }
                    </tr>
                }
            </tbody>
        </table>
     }
}

 

Önerilen table scripti : http://bootstrap-table.wenzhixin.net.cn/

C# Entity Mapping

    public static class EntityMapping
    {
        public static TToEntity To<TFromEntity, TToEntity>(TFromEntity fromEntity) where TToEntity : new()
        {
            var fromProperties = fromEntity.GetType().GetProperties();

            var mappingModel = new TToEntity();

            var toPropertyies = mappingModel.GetType().GetProperties();

            foreach (var toProperty in toPropertyies)
            {
                var propertyInfo = fromProperties.FirstOrDefault(m => m.Name == toProperty.Name);
                if (propertyInfo != null)
                {
                    var value = propertyInfo.GetValue(fromEntity, null);
                    if (value != null)
                    {
                        toProperty.SetValue(mappingModel, value);
                    }
                }
            }
            return mappingModel;
        }

        public static List<TToEntity> To<TFromEntity, TToEntity>(List<TFromEntity> fromEntities) where TToEntity : new()
        {
            var mappingModels = new List<TToEntity>();

            foreach (var fromEntity in fromEntities)
            {
                mappingModels.Add(To<TFromEntity, TToEntity>(fromEntity));
            }
            return mappingModels;
        }
    }

C# WebRequest ile nesne post etme

C# ile istediğim nesneyi direk post edebileceğim hazır bir kütüphane bulamadığım için buraya yazıyorum. Şuan eksikleri var.Güncellenecektir.

 protected List<TEntity> HttpRequestGetList<TEntity>(object data, string url, string method = "POST")
        {
            try
            {
                string parameters = GenerateParameters(data);

                if (method == "GET" && data != null)
                {
                    url += "?" + parameters;
                }

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Method = method;

                if (method == "POST" && data != null)
                {
                    CookieContainer cookies = new CookieContainer();
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    httpWebRequest.CookieContainer = cookies;
                    httpWebRequest.ContentLength = parameters.Length;

                    StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
                    requestWriter.Write(parameters);
                    requestWriter.Close();
                }

                HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse;
                if (response == null) return new List<TEntity>();

                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream == null) return new List<TEntity>();

                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    string readToEnd = reader.ReadToEnd();

                    return JsonConvert.DeserializeObject<List<TEntity>>(readToEnd);
                }
            }
            catch
            {
                return new List<TEntity>();
            }
        }

        protected TEntity HttpRequestGetEntity<TEntity>(object data, string url, string method = "POST") where TEntity : new()
        {
            try
            {
                string parameters = GenerateParameters(data);

                if (method == "GET" && data != null)
                {
                    url += "?" + parameters;
                }

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Method = method;

                if (method == "POST" && data != null)
                {
                    CookieContainer cookies = new CookieContainer();
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    httpWebRequest.CookieContainer = cookies;
                    httpWebRequest.ContentLength = parameters.Length;

                    StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
                    requestWriter.Write(parameters);
                    requestWriter.Close();
                }

                HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse;
                if (response == null) return new TEntity();

                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream == null) return new TEntity();

                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    string readToEnd = reader.ReadToEnd();

                    return JsonConvert.DeserializeObject<TEntity>(readToEnd);
                }
            }
            catch
            {
                return new TEntity();
            }
        }

        private string GenerateParameters(object obj, string prefix = "")
        {
            if (obj == null)
                return "";

            string parameters = "";
            var propertyInfos = obj.GetType().GetProperties();
            foreach (PropertyInfo pInfo in propertyInfos)
            {
                var val = pInfo.GetValue(obj, null);
                if (val != null)
                {
                    if (pInfo.PropertyType.IsArray)
                    {
                        if (val.GetType().IsArray)
                        {
                            Array list = val as Array;
                            if (list != null)
                            {
                                for (int i = 0; i < list.Length; i++)
                                {
                                    parameters += prefix + pInfo.Name + "[" + i + "]=" + list.GetValue(i) + "&";
                                }
                            }
                        }
                    }
                    else if (pInfo.PropertyType.IsClass && pInfo.PropertyType.Name != "String")
                    {
                        parameters += GenerateParameters(val, pInfo.Name + ".") + "&";
                    }
                    else if (!string.IsNullOrWhiteSpace(val.ToString()))
                        parameters += prefix + pInfo.Name + "=" + val + "&";
                }
            }

            return string.IsNullOrWhiteSpace(parameters) ? "" : parameters.Substring(0, parameters.Length - 1);
        }

 

c# türkçe karakter replace

        public string StringReplace(string text)
        {
            text = text.Replace("İ", "I");
            text = text.Replace("ı", "i");
            text = text.Replace("Ğ", "G");
            text = text.Replace("ğ", "g");
            text = text.Replace("Ö", "O");
            text = text.Replace("ö", "o");
            text = text.Replace("Ü", "U");
            text = text.Replace("ü", "u");
            text = text.Replace("Ş", "S");
            text = text.Replace("ş", "s");
            text = text.Replace("Ç", "C");
            text = text.Replace("ç", "c");
            text = text.Replace(" ", "_");
            return text;
        }

Bazı durumlarda (link oluşturmada, dosya yüklemede…) türkçe karakterleri çevirmemiz gerekebilir. Başka değiştirmeniz gereken karakter olursa ekleme yaparsınız artık.

DataTable veriyi SelectList’e aktarma

public SelectList ToSelectList(DataTable table, string valueField, string textField)
{
var list = (from DataRow row in table.Rows
                               select new SelectListItem()
                               {
                                   Text = row[textField].ToString(),
                                   Value = row[valueField].ToString()
                               }).ToList();
return new SelectList(list,"Text","Value")
}

ToSelectList içine listeye çevirmek istediğiniz tabloyu ve gerekli sütun isimlerini yolladıktan sonra metot size SelectList tipinde veri geri dönecektir.

Asp. NET MVC’de View kısmında dropdownlist i doldurmak istiyorsanız da Controller kısmında SelectListi bir ViewBag.ProductClass’a atın view kısmında @Html.DropDownList(“ProductClass”) şeklinde çağırın.