ASP.NET MVC

1. Code Snippets
Drop down list in Create/Edit pages
<%: Html.DropDownListFor(model => model.ProjectId, new SelectList((new Projects.Models.ProjectsEntities().Projects), "Id", "Name"), new { style = "width:200px;" })%>
-or-
<%: Html.DropDownList("IdDriver", (SelectList)ViewData["Users"], new { style = "height:23px;margin-right: 3px; margin-left: 3px;" })%>

Lookup column in List
%: (from m in new FinalArt.Models.FinalArtEntities().Client where m.Id == item.ClientId select m.Name).First()%>
OR
<%: item.ClientProduct.Client.Name %>

CheckBox in Create/Edit pages
<%: Html.CheckBoxFor(model => model.IsActive) %>

CheckBox in List
input type="checkbox" disabled="disabled" <%= (item.IsActive)?"checked":"" %>/

Authorize attribute for actions
[Authorize(Users="admin")]
[Authorize]

Anchor in list
a href="/Client/Index?clientId=<%: item.ClientId %>"

Get Request context outside controller
public static RequestContext CurrentRequestContext
{get{HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
return new RequestContext(context, RouteTable.Routes.GetRouteData(context));}}

Get referer in action
Request.ServerVariables["http_referer"]
Request.UrlReferrer

Html to excel
[Authorize]
public void GetExcel()
{
var html= "...";
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment; filename=xpto.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Write(html);
Response.End();
}

Outerjoin
(from l in left join r in right on l equals r select l).Distinct();

Autocomplete service
[HttpPost]
[Authorize]
public JsonResult FindStates(string searchText, int maxResults)
{
var states = (from task in projectsEntities.Tasks select task.State.Trim()).Distinct();
if(!string.IsNullOrEmpty(searchText))
states = states.Where(s=> s.ToLower() == searchText.ToLower());
var topStates = states.Take(maxResults).ToArray();
return Json(topStates);
}

Cascade drop down list
There are differente way to resolve this problem. One simple way is to change the clients dropdown list value whenever the parents value is changed. This can be done in javascript as shown below.

function Ready() {
$("#ClientId").change(function () {
var clientId = $("#ClientId").val();
PostData("", "", "/ClientProduct/GetClientProductLookup?clientId=" + clientId, null, false, GetClientProductLookupSuccess, null, null, false);
});
}

function GetClientProductLookupSuccess(data) {
$("#ClientProductId").children().remove();
for (var index = 0; index < data.length; ++index) {
var cp = data[index];
var option = $("<option value=\"" + cp.Id + "\">" + cp.Name + "</option>");
$("#ClientProductId").append(option);
}
}

2. Errors and solutions

Browser prompt to save the file for JsonResult
Solution: Change the ContentType of JsonResult to "text/x-json" or "text/plain". By default it is "application/json".

EF4 - Circular reference was detected while serializing an object of type
Modify your controller (or repository) to return object of the other type than the one which has circular reference. For example:
var locations = from loc in crmFrotaEntities.Locations
where loc.Name.ToLower().Contains(searchText.ToLower())
orderby loc.Name
select new {loc.Name, loc.Id};
var topLocations = locations.Take(maxResults).ToArray();
return Json(topLocations);
OR
return Json(location); -> return Json(new {location.id, location.name});

System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced.
Even if we have added reference we may see this error if we are using Entity Framework objects in UI (.aspx, .ascx) pages and iterating through it. To resolve this issue it is necessary to add reference in web.config.

<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>

3. How Tos

public static void SendEmail(string to, string subject, string body, string fileToAttachFullName="", string bcc="", bool isBodyHtml = true, string gmailFrom = "xpto@gmail.com", string gmailPassword = "myPassword"){
using (MailMessage mail = new MailMessage(gmailFrom, to, subject, body))
{
if (!string.IsNullOrEmpty(bcc))
mail.Bcc.Add(new MailAddress(bcc));
if (!string.IsNullOrEmpty(fileToAttachFullName))
mail.Attachments.Add(new Attachment(fileToAttachFullName));
mail.IsBodyHtml = isBodyHtml;
var client = new SmtpClient("smtp.gmail.com")
{
Credentials = new NetworkCredential(gmailFrom, gmailPassword),
EnableSsl = true
};
client.Send(mail);
}
}

CustomError
protected void Application_Error(object sender, EventArgs e){
Response.Redirect("/Home/Error?message=" + Server.GetLastError());
}

PDF page to Image
This can be done using a third party library, for example ITextSharp. ITextSharp can be downloaded from here.

Multiple autocomplete
There is a jQuery plugin which can do it. You can download it here
Just use multiple=true.

HtmlToPdf (havent tested it yet)
Encoding Decoding base64(I have used this for Encoding/Decoding URL for return URLs)


4. Tutorials

5. Blogs

6. Websites


7. Books


8. Downloads

No comments:

Post a Comment