Posts Tagged ‘Microsoft MVC’
SelectListItem Class for Web Applications and MVC Applications at ASP.NET
I am developing to new web site with ASP.NET MVC 3. Therefore I need a SelectListItem class for ajax operations. So i wrote a new generic class. In case you guys need it i thought I’d share it.
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace WebSite.Models.ViewEntities
{
/// <summary>
/// Select List Item Entity
/// </summary>
/// <typeparam name="T">Text Property Type</typeparam>
/// <typeparam name="U">Value Property Type</typeparam>
[JsonObject]
public class SelectListItem<T, U>
{
/// <summary>
/// Initializes a new instance of the <see cref="SelectListItem<T, U>"/> class.
/// </summary>
public SelectListItem()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SelectListItem<T, U>"/> class.
/// </summary>
/// <param name="text">The text.</param>
public SelectListItem(T text)
{
Text = text;
}
/// <summary>
/// Initializes a new instance of the <see cref="SelectListItem<T, U>"/> class.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="value">The value.</param>
public SelectListItem(T text, U value)
{
Text = text;
Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="SelectListItem<T, U>"/> class.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="value">The value.</param>
/// <param name="isSelected">if set to <c>true</c> [is selected].</param>
public SelectListItem(T text, U value, bool isSelected)
{
Text = text;
Value = value;
IsSelected = isSelected;
}
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>
/// The value.
/// </value>
[JsonProperty]
public U Value { get; set; }
/// <summary>
/// Gets or sets the text.
/// </summary>
/// <value>
/// The text.
/// </value>
[JsonProperty]
public T Text { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is selected.
/// </summary>
/// <value>
/// <c>true</c> if this instance is selected; otherwise, <c>false</c>.
/// </value>
[JsonProperty]
public bool IsSelected { get; set; }
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var builder = new StringBuilder();
builder.Append("{ Value = ");
builder.Append(Value);
builder.Append(", Text = ");
builder.Append(Text);
builder.Append(", IsSelected = ");
builder.Append(IsSelected);
builder.Append(" }");
return builder.ToString();
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="value">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
{
var type = value as SelectListItem<T, U>;
return (type != null) && EqualityComparer<U>.Default.Equals(type.Value, Value) && EqualityComparer<T>.Default.Equals(type.Text, Text) && EqualityComparer<bool>.Default.Equals(type.IsSelected, IsSelected);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
var num = 0x7a2f0b42;
num = (-1521134295 * num) + EqualityComparer<U>.Default.GetHashCode(Value);
num = (-1521134295 * num) + EqualityComparer<T>.Default.GetHashCode(Text);
return (-1521134295 * num) + EqualityComparer<bool>.Default.GetHashCode(IsSelected);
}
}
}
Uploadify ile Firefox upload problemi
Uploadify dosya yüklemesi için kullandığımız en güzel araçlardan biri. Ancak geçen gün bu sistemle dosya yüklemesi yaparken bir problem ile karşılaştım. Yükleme işlemi başlamadan HTTP 302 hatası veriyordu. Daha doğrusu bu hata değil biliyorsunuz. Sistemde session cookie’si bulunamadığı için bizi login sayfasına yönlendiren bir HTTP geri dönüş değeri. Bu durum ile ilgili internette bir araştırma yaptım ve bunun flash plugin’lerinden kaynaklanan bir problem olduğunu öğrendim. Sorun tam olarak şu idi, flash internet explorer dışındaki plug’inlerinde browser cookie’lerini kullanmıyordu. Yani siz siteye login oldunuz, gerekli bütün işlemler ve cookie’ler browser’a yüklendi, ancak bu durumdan sonra flash ile site üzerine bir dosya göndermeye kalktığınızda o zaman flash browser’daki cookie’leri sunucuya göndermediği için flash’ın bu isteği sunucu tarafından anonim bir istek gibi algılanıp, login sayfasına yönlendirilerek sonlandırılıyor.
Tamam sorunu anladık, ama nasıl çözeceğiz. Ben uploadify kullandığım için onun için bir çözüm aradım ve şu linkteki çözümü buldum : http://stackoverflow.com/questions/1729179/uploadify-session-and-authentication-with-asp-net-mvc
Burada sevgili arkadaşımız flash’ın cookie’yi alamaması dolayısıyla cookie’de giden bilgiyi post verisi içerisine ekleyip, bu şekilde bilgiyi karşıya iletmekte. böylece cookie yok ise bu bilgi ile server flash istemcisini tanımakta. güzel bir çözüm bende bu çözümü aşağıda paylaşıyorum :
önce uploadify tanımımızda bazı bilgi eklemeleri yapmamız gerekiyor :
<script>
var auth = "<% = Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>";
var ASPSESSID = "<%= Session.SessionID %>";
$("#uploadifyLogo").uploadify({
...
scriptData: { ASPSESSID: ASPSESSID, AUTHID: auth }
});
Sonrada global.asax dosyasına aşağıdaki kodu eklemeliyiz :
protected void Application_BeginRequest(object sender, EventArgs e)
{
/* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SessionId";
if (HttpContext.Current.Request.Form[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
}
else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
}
}
catch
{
}
try
{
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (HttpContext.Current.Request.Form[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
}
else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
}
}
catch
{
}
}
private void UpdateCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (null == cookie)
{
cookie = new HttpCookie(cookie_name);
}
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}
böylece problem çözülür.
Ayrıca başka bir kaynakta MVC tarafındaki çözüm anlatılmış: http://www.uploadify.com/forums/discussion/6494/problem-with-uploadify-the-upload-does-not-start/p1
MVC ile ilgili güzel bir makale serisi
MVC ile ilgili güzel bir makale serisi buldum ve hemen paylaşmak istedim.
The ASP.NET MVC 2 Series
- Introduction to ASP.NET MVC 2.0 In this article, we’ll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
- ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we’ll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
- ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
- ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
- ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
- ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
- ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
- ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it’s quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we’ll see that all here soon.
- ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
- ASP.NET MVC 2.0 and ADO.NET Entity Framework – Part 1 In this article, we’ll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
- ASP.NET MVC 2.0 and ADO.NET Entity Framework – Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We’re going to examine using these API features to create a generic version of of a data repository.
- Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
MVC Partial Rendering
MVC Partial rendering ile ilgili bulduğum birkaç güzel makalenin adresini paylaşmak istiyorum:
- Partial Rendering with ASP.NET MVC and jQuery
Yesterday, I wrote a post detailing how easy we can invoke an ASP.NET MVC controller action from JavaScript using jQuery. Lets up the ante a bit, and see if we can’t use the same approach to get some partial rendering going. To accomplish this, we’ll use a fact about the RenderViewResult class that hasn’t got a lot of attention so far – the fact that its View propetry can be set to point at a UserControl, not just a WebForm. When doing so, only the user control will be rendered – which sounds like exactly what we need for doing partial rendering.. - Partial Requests in ASP.NET MVC
In your ASP.NET MVC application, it can be tricky to combine multiple independent “widgets” on the same page. That’s because a WebForms-style hierarchy of independent controls clashes awkwardly against a purist’s one-way MVC pipeline. Widgets? I’m taking about that drill-down navigation widget you want in your sidebar, or the “most recent forum posts” widget you’d put in the page footer. Things that need to fetch their own data independently of the page that hosts them. - Ajax with the ASP.NET MVC Framework
This post presents a few basic Ajax features (similar to partial rendering and behaviors in terms of concepts) running on top of the ASP.NET MVC framework… some early ideas, experimentation and app-building results. - ASP.NET MVC: Using UserControls Usefully
This post is in response to a forum user, who is wondering how to properly use a ViewUserControl: I’m sorry if this is a really silly question, but I’m having a hard time grokking what the right usage of a ViewUserControl looks like. Does one invoke the RenderView from a controller?
MVC: Farklı Area’lar altında aynı isme sahip Controller’lar var ise
Böyle bir durumda büyük ihtimalle sistem size hangi controller’ı kullanmam lazım belirleyemedim diye bir hata verecektir. Aynı zamanda MapRoute ismindeki metodun(ki kendisi Global.asax.cs içerisinde ve her Area’nın ….AreaRegistration isimli sınıfının içinde yer alır.) namespace’leri tanımlayabileceğimiz bir overload’ını kullanmamızı önerir. Her aynı isime sahip controller’ın bulunduğu alanlarda, controller’ın namespace’ini RouteMap fonksiyonu ile tanımlamanız gerekir.
Örneğin :
Ana Projem içinde bir tane Pages diye bir controller’ım var. Ayrıca Admin ismini verdiğim bir area’m ve bunun içinde de Pages isminde bir controller’ım var. her ikisi maalesefki birbirleri ile çakıştıkları için MVC uygulamam çalışmıyor. O zaman yapmam gerekenler şunlar :
1. Global.asax.cs dosyası üzerinde yer alan :
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
satırını
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new []{"DemoProje.Controllers"}
);
olarak değiştiririm.
Aynı işlemi area için yazılan AdminAreaRegistration sınıfının içinde de yaparım:
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
şeklinde olan satırı
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "DemoProje.Areas.Admin.Controllers" }
);
şekline getiririm.
Tatam …. işlem tamam, artık problem çözüldü
