What's wrong with Razor markup? - asp.net-mvc-3

I am trying to learn MVC and using samples from the "Pro ASP .net MVC 2". Only I'm trying to write everything in MVC3.
first I had some problem with #Html.RenderAction thing, I changed it to #Html.Action - it did the trick.
Now I have a problem. Could you tell me why ascx view works and similar Razor doesn't?
ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<SportsStore.WebUI.Models.NavLink>>" %>
<% foreach (var link in Model) { %>
<%: Html.RouteLink(link.Text, link.RouteValues, new Dictionary<string, object> {
{ "class", link.IsSelected ? "selected" : null }
}) %>
<% } %>
Razor:
#model IEnumerable<SportsStore.WebUI.Models.NavLink>
#foreach (var link in Model)
{
Html.RouteLink(link.Text, link.RouteValues, new Dictionary<string, object> { { "class", link.IsSelected ? "selected" : null } });
}

The Html.RouteLink method returns an IHtmlString.
It does not write anything to the page.
You need to write the returned IHtmlString to the page by writing #Html.RouteLink(...).
This is Razor's equivalent to the <%: Html.RouteLink(...) %> in the ASCX page.

Try this:
#model IEnumerable<SportsStore.WebUI.Models.NavLink>
#foreach (var link in Model)
{
#Html.RouteLink(link.Text, link.RouteValues, new { #class = link.IsSelected ? "selected" : string.empty });
}

Related

Best way to pass single value from view to controller

I have a form that posts a single value, but I cant seem to get it to the controller. I have verified the value exists in the form, but it arrives at the controller as null. Here is the form post:
<%Html.BeginForm("SaveRecord", "NewApplicant", FormMethod.Post, new { id = Model.PersonModel.ApplicantID } ); %>
<%: Html.Hidden("NewId", Model.PersonModel.ApplicantID) %>
<input type="submit" class="SKButton" value="Save" title="Save this new application as a unique record." />
<% Html.EndForm(); %>
and here is the contoller action:
public ActionResult SaveRecord(NewApplicantViewModel model)
{
int NewAppId = model.PersonModel.ApplicantID;
I have also tried:
public ActionResult SaveRecord(int NewId)
{
model.PersonModel.ApplicantID = NewId;
These must be a simple fix, and I want to pass the id in the model, dont want to use ajax. Thoughts?
Try using:
<%: Html.HiddenFor(model => model.PersonModel.ApplicantID) %>

Telerik Grid paging and Sorting in ASP.Net MVC3(aspx engine)

I am using Telerik Rad Grid in MVC3(aspx engine) like:-
This is my Controller:-
[HttpGet]
[GridAction(EnableCustomBinding = true)]
public ActionResult Search()
{
SearchViewModel searchViewModel = new SearchViewModel(this.serviceInvoker);
SearchRequest searchRequest = new SearchRequest();
searchViewModel.Initialize();
ViewData["TotalRecord"] = SearchViewModel.SearchResponses.Count();
return View(searchViewModel);
}
This is my ViewModel:-
<% using (Html.BeginForm("CaseSearch", "AdvanceSearch", FormMethod.Post, new { #class "formStyle" }))
{ %>
<div class="boxPanel">
<fieldset>
<legend></legend>
<ul class="floatleft width25" >
<div class="floatleft">
<% Html.RenderPartial("PartialViewCaseSearch"); %>
</div>
</fieldset>
<% } %>
This is my Partial View Telerik Grid:-
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%# Import Namespace="ABC.DataContracts.Messages" %>
<%= Html.Telerik().Grid((IEnumerable<SearchResponse>)Model.SearchResponses)
.Name("CaseSearchGrid")
.Columns(columns =>
{
columns.Bound(grid => grid.RowNumber);
columns.Bound(grid => grid.CreatedOn).Format("{0:dd/MM/yyyy}");
columns.Bound(grid => grid.CaseReference);
})
.DataBinding(dataBinding => dataBinding.Ajax().Select("Search", "AdvanceSearch"))
.EnableCustomBinding(true)
.BindTo((IEnumerable<SearchResponse>)Model.SearchResponses)
.Pageable(paging => paging.Enabled(true))
%>
SearchResponse is my object which is result of search request.
I have to implement Custom Server Ajax binding with Server side Paging ans Sorting. I have implemented Paging and sorting in my stored procedure. but when ever i am clicking on page index or sorting column its not returning proper data and throughing error like. " Invalid JSON request".
Please also assist me how to pass the sort column name and page index to my controller.
Thanks.
Your AdvanceSearch() action should take GridCommand as it's parameter, so you know what sorting to apply. Take a look at Telerik documentation.
You can also attack the debugger in order to see what the actual exception on the server is.

ASP.Net MVC ViewData Issue

I have the following code:
private Models.mediamanagerEntities dataModel = new Models.mediamanagerEntities();
public ActionResult Index(FormCollection form)
{
ViewData.Model = (from m in dataModel.Customers select m.Type.Items).ToList();
return View();
}
View:
%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<Project_Name.Models.Item>>" %>
<% foreach (var m in ViewData.Model)
{ %>
Title: <%= m.Title %>
<% } %>
I get the following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[System.Data.Objects.DataClasses.EntityCollection1[Project_Name.Models.Item]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Project_Name.Models.Item].
I'm not too sure what it happening here or how to rectify it, Thanks.
Your LINQ is creating a list like this List<EntityCollection<Item>>, when your view wants List<Item>.
I don't know query syntax for LINQ very well, but this is how you'd get what you want with function syntax:
ViewData.Model = dataModel.Customers.SelectMany(c => c.Type.Items).ToList();
That will take the many Items under each customer and flatten them into one list of Items.
Replace this line:
ViewData.Model = (from m in dataModel.Customers select m.Type.Items).ToList();
with the following:
ViewData.Model = dataModel.Type.ToList();

Razor syntax to declare action that renders html

I'm trying to create an action that renders some html in the razor view engine. This was pretty easy in the webforms engine but I'm having some issues with razor. Here is the simplest form of what I'm trying to accomplish using the webforms engine:
<% var myAction = new Action<HtmlHelper<int>>((helper) => { %>
<div>
<%= helper.ViewData.Model %>
</div>
<%}); %>
The closest I've come in the razor view engine is:
#{var myAction = new Action<HtmlHelper<int>>((help) =>
{
#<div>
#help.ViewData.Model
</div>;
});
}
This gives a "CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement" error.
Any help would be appreciated. Thanks.
#{
Func<dynamic, object> myAction =
#<div>
#item.ProductName
</div>;
}
#myAction(Model)
You may also checkout the following blog post.
UPDATE:
You may also do this:
#{
Func<HtmlHelper<int>, object> myAction = #<div>#item.ViewData.Model</div>;
}
or:
#{
Func<dynamic, object> myAction = #<div>#item.ViewData.Model</div>;
}
and to invoke:
#myAction(someInstanceOfTheRequiredHelper)

How can I get access to a variable in a View which was created in a Controller?

How can I get access to a variable in a View which was created in a Controller?
Either put the variable into the Model that you are using for your View
Or use a ViewBag variable - e.g. from http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewBag.ListColors = colors; //colors is List
ViewBag.DateNow = DateTime.Now;
ViewBag.Name = "Hajan";
ViewBag.Age = 25;
return View();
}
and
<p>
My name is
<b><%: ViewBag.Name %></b>,
<b><%: ViewBag.Age %></b> years old.
<br />
I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewBag.ListColors) { %>
<li>
<font color="<%: color %>"><%: color %></font>
</li>
<% } %>
although hopefully you'll be using Razor :)
You need to send the variable to the view in the ViewModel (the parameter to the View() method) or the TempData dictionary.
You can add it to the ViewData[] dictionary or the (newer) ViewBag dynamic.
In your controller:
ViewData['YourVariable'] = yourVariable;
// or
ViewBag.YourVariable = yourVariable;
In your view:
<%: ViewData["yourVariable"] %>
// or
<%: ViewBag.YourVariable %>

Resources