Hi!
Have you ever had this problem? You are on a certain page and you want to call a different Controller?
@Html.ActionLink([The name that will appear on the webpage], [The Action], [The name of the controller], [The parameters (Example.. new { code = item.code})], null)
Text, Action, Controller, Parameters, HttpObj.
The secret is to use the right overload. On the last parameter you have to pass null. If you use the overload with three parameters, for some reason I don't know, it doesn't work.
That's it!
Mostrando postagens com marcador MVC3. Mostrar todas as postagens
Mostrando postagens com marcador MVC3. Mostrar todas as postagens
segunda-feira, 14 de abril de 2014
sexta-feira, 27 de setembro de 2013
Very simple way to transform HTML into Excel - MVC3
Hi!
I was wondering about how to transform HTML into Excel format using Razor. I've been searching on the Internet and a came out with the solution showed on picture 1.
1 - Create a view called Report.cshtml
2 - In the controller I created two methods
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var 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();
}
}
public ActionResult TerritoriesInExcel(string searchString)
{
string lStrSearchString = searchString == null ? "" : searchString; ;
var myTerritories = (new TerritoriesDAO()).getAll(1, true, lStrSearchString);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=myTerritories.xls");
Response.ContentType = "application/excel";
Response.Write(RenderRazorViewToString("Report",myTerritories));
Response.End();
return View(myTerritories);
}
3 - I have a Index.cshtml in the folder Views
So, the sequence is
Index -> Controller -> Change header response -> Transform Report.cshtml into a string -> make the call -> return to Index.cshtml.
Two main points: The change that was made to the header of response and the transformation of the view into a string.
Notice that RenderRazorViewToString is a generic function and can be used in whatever context.
picture 1.
References
http://amitpatelit.com/2013/05/22/export-to-excel-in-asp-net-mvc/
http://akinyusufer.blogspot.in/2011/05/razor-render-mvc3-view-render-to-string.html
I was wondering about how to transform HTML into Excel format using Razor. I've been searching on the Internet and a came out with the solution showed on picture 1.
1 - Create a view called Report.cshtml
2 - In the controller I created two methods
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var 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();
}
}
public ActionResult TerritoriesInExcel(string searchString)
{
string lStrSearchString = searchString == null ? "" : searchString; ;
var myTerritories = (new TerritoriesDAO()).getAll(1, true, lStrSearchString);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=myTerritories.xls");
Response.ContentType = "application/excel";
Response.Write(RenderRazorViewToString("Report",myTerritories));
Response.End();
return View(myTerritories);
}
3 - I have a Index.cshtml in the folder Views
So, the sequence is
Index -> Controller -> Change header response -> Transform Report.cshtml into a string -> make the call -> return to Index.cshtml.
Two main points: The change that was made to the header of response and the transformation of the view into a string.
Notice that RenderRazorViewToString is a generic function and can be used in whatever context.
picture 1.
References
http://amitpatelit.com/2013/05/22/export-to-excel-in-asp-net-mvc/
http://akinyusufer.blogspot.in/2011/05/razor-render-mvc3-view-render-to-string.html
quarta-feira, 25 de setembro de 2013
Autocomplete - MVC3, RAZOR, LINQ, JQuery
Hi!
This infernal autocomplete took me two days, but I finally made it. Territories is an entity from Northwind schema.
DAO
public IQueryable<string> getTerritoryDescription(string searchstring)
{
NorthwindDataContext lObjND = new NorthwindDataContext();
var suggestions = from p in lObjND.Territories select p.TerritoryDescription;
var namelist = suggestions.Where(n => n.ToLower().StartsWith(searchstring.ToLower()));
return namelist;
}
CONTROLLER
public JsonResult AutoCompleteSuggestions(string term)
{
var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Attention: if you try to use another parameter name instead of term, it will not work. Something like (string searchstring) doesn't work.
VIEW
<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$("#SearchString").autocomplete({
source: "/Territories/AutocompleteSuggestions",
minLength: 1 });
});
</script>
.
.
@using (Html.BeginForm())
{
<p>
Find by name: @Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
And that's it!
This infernal autocomplete took me two days, but I finally made it. Territories is an entity from Northwind schema.
DAO
public IQueryable<string> getTerritoryDescription(string searchstring)
{
NorthwindDataContext lObjND = new NorthwindDataContext();
var suggestions = from p in lObjND.Territories select p.TerritoryDescription;
var namelist = suggestions.Where(n => n.ToLower().StartsWith(searchstring.ToLower()));
return namelist;
}
CONTROLLER
public JsonResult AutoCompleteSuggestions(string term)
{
var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Attention: if you try to use another parameter name instead of term, it will not work. Something like (string searchstring) doesn't work.
VIEW
<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$("#SearchString").autocomplete({
source: "/Territories/AutocompleteSuggestions",
minLength: 1 });
});
</script>
.
.
@using (Html.BeginForm())
{
<p>
Find by name: @Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
And that's it!
terça-feira, 24 de setembro de 2013
MVC3-RAZOR-LINQ :: searchstring appears null - ERROR
There are many examples of AutoComplete funcionality on the internet like this one bellow
This is a typical method of a controler
public JsonResult AutoCompleteSuggestions(string searchstring)
{
var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Problem is: when the method is called by the view, search string always comes null.
Debugging on firefox you're gona find out that the parameter name is term. So, if you name it as searchstring, it will always be null. Why this happens? I have no idea.
--
[16:21:27.306] GET http://localhost:3289/Territories/AutocompleteSuggestions?term=w [HTTP/1.1 200 OK 0 ms]
--
Change the parameter name to term and magically the value will appear!
public JsonResult AutoCompleteSuggestions(string term)
{
var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
This is a typical method of a controler
public JsonResult AutoCompleteSuggestions(string searchstring)
{
var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Problem is: when the method is called by the view, search string always comes null.
Debugging on firefox you're gona find out that the parameter name is term. So, if you name it as searchstring, it will always be null. Why this happens? I have no idea.
--
[16:21:27.306] GET http://localhost:3289/Territories/AutocompleteSuggestions?term=w [HTTP/1.1 200 OK 0 ms]
--
Change the parameter name to term and magically the value will appear!
public JsonResult AutoCompleteSuggestions(string term)
{
var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
segunda-feira, 23 de setembro de 2013
Dynamic OrderBy using LINQ
It took me hours to figure out how to make dynamic orderby, using LINQ. It's not easy at all.
There are a lot of abstraction which almost fried my brain.
So let's do it step by step.
As schema of database I'm using northwind.
The table I'm using is Territory.
But like me, you probably came to the conclusion that using the model created by LINQ through database bind is not a good idea. So, I created a class called TerritoryModel. This class is in the folder RAZOR. That's why you're seeing RAZOR.Models.TerritoryModel as the type of the IOrderedEnumerable result.
Notice that the result of the method getAll is a IOrderedEnumerable and not a IQueryable, which would be expected.
1 - Variables to define.
//The LINQ context
NorthwindDataContext lObjDC = new NorthwindDataContext();
//The function you'll need to dynamically change the field by which you're going to order your result.
Func<TerritoryModel, object> selector = null;
//The variable which will receive the result of the ordered result.
IOrderedEnumerable<TerritoryModel> lMT = null;
2 - Swtich
//I wrote a very simple switch. This is the part of the program that does the trick of dynamically change the column which will order the table Territory.
#region Selector
switch (pIntSortBy)
{
case 1:
selector = a => a.TerritoryID;
break;
case 2:
selector = a => a.TerritoryDescription;
break;
case 3:
selector = a => a.RegionDescription;
break;
}
3 - The IQueryable select
var myTerritories = (from te in lObjDC.Territories
join re in lObjDC.Regions
on te.RegionID equals re.RegionID
select new
{
TerritoryID = te.TerritoryID,
TerritoryDescription = te.TerritoryDescription,
RegionDescription = re.RegionDescription
});
4 -The orderBy. An IOrderedEnumerable result.
if (pBlnIsAsc)
{
lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderBy(selector);
}
else
{
lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderByDescending(selector);
}
Why am'I working with IOrderedEnumerable? Well, in the moment you type OrderBy or OrderByDescending, it stops to be IQueryable and starts to be IOrderedEnumerable.
In the end, we'll have a function like that:
public IOrderedEnumerable<RAZOR.Models.TerritoryModel> getAll(int pIntSortBy, bool pBlnIsAsc)
{
NorthwindDataContext lObjDC = new NorthwindDataContext();
Func<TerritoryModel, object> selector = null;
IOrderedEnumerable<TerritoryModel> lMT = null;
#region Selector
switch (pIntSortBy)
{
case 1:
selector = a => a.TerritoryID;
break;
case 2:
selector = a => a.TerritoryDescription;
break;
case 3:
selector = a => a.RegionDescription;
break;
}
#endregion
var myTerritories = (from te in lObjDC.Territories
join re in lObjDC.Regions
on te.RegionID equals re.RegionID
select new
{
TerritoryID = te.TerritoryID,
TerritoryDescription = te.TerritoryDescription,
RegionDescription = re.RegionDescription
});
if (pBlnIsAsc)
{
lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderBy(selector);
}
else
{
lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderByDescending(selector);
}
return lMT;
}
Et voilà!
There are a lot of abstraction which almost fried my brain.
So let's do it step by step.
As schema of database I'm using northwind.
The table I'm using is Territory.
But like me, you probably came to the conclusion that using the model created by LINQ through database bind is not a good idea. So, I created a class called TerritoryModel. This class is in the folder RAZOR. That's why you're seeing RAZOR.Models.TerritoryModel as the type of the IOrderedEnumerable result.
Notice that the result of the method getAll is a IOrderedEnumerable and not a IQueryable, which would be expected.
1 - Variables to define.
//The LINQ context
NorthwindDataContext lObjDC = new NorthwindDataContext();
//The function you'll need to dynamically change the field by which you're going to order your result.
Func<TerritoryModel, object> selector = null;
//The variable which will receive the result of the ordered result.
IOrderedEnumerable<TerritoryModel> lMT = null;
2 - Swtich
//I wrote a very simple switch. This is the part of the program that does the trick of dynamically change the column which will order the table Territory.
#region Selector
switch (pIntSortBy)
{
case 1:
selector = a => a.TerritoryID;
break;
case 2:
selector = a => a.TerritoryDescription;
break;
case 3:
selector = a => a.RegionDescription;
break;
}
3 - The IQueryable select
var myTerritories = (from te in lObjDC.Territories
join re in lObjDC.Regions
on te.RegionID equals re.RegionID
select new
{
TerritoryID = te.TerritoryID,
TerritoryDescription = te.TerritoryDescription,
RegionDescription = re.RegionDescription
});
4 -The orderBy. An IOrderedEnumerable result.
if (pBlnIsAsc)
{
lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderBy(selector);
}
else
{
lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderByDescending(selector);
}
Why am'I working with IOrderedEnumerable? Well, in the moment you type OrderBy or OrderByDescending, it stops to be IQueryable and starts to be IOrderedEnumerable.
In the end, we'll have a function like that:
public IOrderedEnumerable<RAZOR.Models.TerritoryModel> getAll(int pIntSortBy, bool pBlnIsAsc)
{
NorthwindDataContext lObjDC = new NorthwindDataContext();
Func<TerritoryModel, object> selector = null;
IOrderedEnumerable<TerritoryModel> lMT = null;
#region Selector
switch (pIntSortBy)
{
case 1:
selector = a => a.TerritoryID;
break;
case 2:
selector = a => a.TerritoryDescription;
break;
case 3:
selector = a => a.RegionDescription;
break;
}
#endregion
var myTerritories = (from te in lObjDC.Territories
join re in lObjDC.Regions
on te.RegionID equals re.RegionID
select new
{
TerritoryID = te.TerritoryID,
TerritoryDescription = te.TerritoryDescription,
RegionDescription = re.RegionDescription
});
if (pBlnIsAsc)
{
lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderBy(selector);
}
else
{
lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderByDescending(selector);
}
return lMT;
}
Et voilà!
Assinar:
Postagens (Atom)