DatePicker Dropdown Html Helper examples ve jquery-json , ajax post

public static MvcHtmlString DatePickerDropDowns(this HtmlHelper html,

          string dayName, string monthName, string yearName,
          int? beginYear = null, int? endYear = null,
          int? selectedDay = null, int? selectedMonth = null, int? selectedYear = null, bool localizeLabels = true)
      {
          var daysList = new TagBuilder("select");
          var monthsList = new TagBuilder("select");
          var yearsList = new TagBuilder("select");
 
          daysList.Attributes.Add("name", dayName);
          monthsList.Attributes.Add("name", monthName);
          yearsList.Attributes.Add("name", yearName);
 
          var days = new StringBuilder();
          var months = new StringBuilder();
          var years = new StringBuilder();
 
          string dayLocale, monthLocale, yearLocale;
          if (localizeLabels)
          {
              var locService = new LocaleService();
              dayLocale = locService.GetResource("Day");
              monthLocale = locService.GetResource("Month");
              yearLocale = locService.GetResource("Year");
          }
          else
          {
              dayLocale = "Day";
              monthLocale = "Month";
              yearLocale = "Year";
          }
 
          days.AppendFormat("<option value='{0}'>{1}</option>", "0", dayLocale);
          for (int i = 1; i <= 31; i++)
              days.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
                  (selectedDay.HasValue && selectedDay.Value == i) ? " selected=\"selected\"" : null);
 
 
          months.AppendFormat("<option value='{0}'>{1}</option>", "0", monthLocale);
          for (int i = 1; i <= 12; i++)
          {
              months.AppendFormat("<option value='{0}'{1}>{2}</option>",
                                  i, 
                                  (selectedMonth.HasValue && selectedMonth.Value == i) ? " selected=\"selected\"" : null,
                                  CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(i));
          }
 
 
          years.AppendFormat("<option value='{0}'>{1}</option>", "0", yearLocale);
 
          if (beginYear == null)
              beginYear = DateTime.UtcNow.Year - 100;
          if (endYear == null)
              endYear = DateTime.UtcNow.Year;
 
          for (int i = beginYear.Value; i <= endYear.Value; i++)
              years.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
                  (selectedYear.HasValue && selectedYear.Value == i) ? " selected=\"selected\"" : null);
 
          daysList.InnerHtml = days.ToString();
          monthsList.InnerHtml = months.ToString();
          yearsList.InnerHtml = years.ToString();
 
          return MvcHtmlString.Create(string.Concat(daysList, monthsList, yearsList));
      }

Ayrıca Session timeOut olunca işe yarayan bir kok

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class MyAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            OnAuthorizationHelp(filterContext);
        }
 
        internal void OnAuthorizationHelp(AuthorizationContext filterContext)
        {
 
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.HttpContext.Response.StatusCode = 401;
                    filterContext.HttpContext.Response.End();
                }
            }
        }
    }
$(document).ajaxError(function (xhr, props) {
           if (props.status === 401) {
               location.reload();
           }
       });

 

Web.Configde aşğıdaki ayarıda yapmak gerekiyor tabii.

<forms loginUrl="~/Account/Login" timeout="30"  />

 

Ayrıca

Jquery-json post örneği verelim..

Global.asax da eklemizi yapalım..

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

Sonra poco classlarımızı oluşturalım

[Serializable]
   public class PersonInputModel
   {
       public string Name { get; set; }
       public int Age { get; set; }
       public List<Book> Books { get; set; }
   }
 
   [Serializable]
   public class Book
   {
       public int Id { get; set; }
       public string Name { get; set; }
   }

Action methodumuzu hazırlayalım..

[HttpPost]
        public ActionResult Save(PersonInputModel inputModel)
        {
            if (ModelState.IsValid)
            {
                var message = string.Format("İsmi '{0}' yaşı '{1}' olan kişi kaydedildi ayrıca '{2}' adet kitabı var."
                  , inputModel.Name, inputModel.Age, inputModel.Books.Count);
                return Json(new PersonViewModel { Message = message });
            }
            var errorMessage = ModelState.Keys.Select(key => ModelState[key].Errors.FirstOrDefault()).Where(error => error != null).Aggregate("<div class=\"validation-summary-errors\">" + "The following errors occurred:<ul>", (current, error) => current + ("<li class=\"field-validation-error\">" + error.ErrorMessage + "</li>"));
            errorMessage += "</ul>";
            return Json(new PersonViewModel { Message = errorMessage });
        }
<input type="text" value="Name" id="Name" />
<input type="text" value="10" id="Age" />
<input type="button" value="Create" id="personCreate" />
@section scripts
{
    <script type="text/javascript">
        $(function () {
            $("#personCreate").click(function () {
                var person = {};
                person.Name = $("#Name").val();
                person.Age = $("#Age").val();
 
                var books = [];
 
                var book = {};
 
                book.Id = "1";
                book.Name = "Katre-i Matem";
 
                var book2 = {};
 
                book2.Id = "1";
                book2.Name = "Olasılıksız";
 
                books.push(book);
                books.push(book2);
 
                person.books = books;
 
                var json = $.toJSON(person);
 
                $.ajax({
                    url: '/home/save',
                    type: 'POST',
                    dataType: 'json',
                    data: json,
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        // get the result and do some magic with it
                        var message = data.Message;
                        alert(message);
                    }
                });
            });
        });
    </script>
}

Tabii java script kodunun çalışması için jquery-json{version} eklentisi olması unutmuyoruz.

referans:  http://www.kalbeyn.com/

 

Add comment

The file '/Custom/Widgets/Calendar/widget.cshtml' does not exist.The file '/Custom/Widgets/Category list/widget.cshtml' does not exist.The file '/Custom/Widgets/Tag cloud/widget.cshtml' does not exist.The file '/Custom/Widgets/Page List/widget.cshtml' does not exist.The file '/Custom/Widgets/Month List/widget.cshtml' does not exist.