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)
Related
When using LoadContentFrom in my Kendo.Tooltip, the tooltip is always empty, all I see is a grey box the size I specified. It does go to the controller to get the data (verified with breakpoint), but after that, nothing.
If I use ContentTemplateId instead, it shows the template, but I really need to get some dynamic data from the server.
What am I missing to fix this?
Thanks
<%:Html.Kendo().Tooltip()
.For("#alertPanel")
.LoadContentFrom("AlertsDetails", "Home")
.Width(320).Height(320)
%>
Controller:
public ActionResult AlertsDetails()
{
List<object> list = new List<object>();
//fill list with data ...
ViewBag.title = "New alerts";
return PartialView(list);
}
Answer: You can't return data the way I was doing. You need to format the data server-side in an HTML string and set the result in the ViewBag.
public ActionResult AlertsDetails()
{
ViewBag.Title = "<a href='#'>A link</a>";
return PartialView();
}
and
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%= ViewBag.Title%>
That's it...
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.
If I use the following Controller method:
public ActionResult Menu()
{
// do stuff...
return PartialView("viewName", navLinks);
}
calling the partial view in _Layout.cshtml like this:
<div id="categories">
#{ Html.Action("Menu", "Nav"); }
</div>
With the following ASCX partial view:
<%# Control Language="C#"
Inherits="ViewUserController<IEnumerable<MyDataType>>" %>
<% foreach(var link in Model) { %>
<%: Html.Route.Link(link.Text, link.RouteValues) %>
<% } %>
everything works fine. Yay.
BUT, if I use either of the following RAZOR partial views:
#model IEnumerable<MyDataType>
#foreach(var link in Model){
Html.RouteLink(link.Text, link.RouteValues);
}
or...
#model IEnumerable<MyDataType>
#{
Layout = null;
}
#foreach(var link in Model){
Html.RouteLink(link.Text, link.RouteValues);
}
I get nothing. there's no exception thrown, I just don't get anything rendered. I know the problem isn't with the controller method (it works just great with the ASCX partial view).
What's going on here?
Try changing this:
#foreach(var link in Model){
Html.RouteLink(link.Text, link.RouteValues);
}
to this:
#foreach(var link in Model){
#Html.RouteLink(link.Text, link.RouteValues);
}
It looks like without the # the method is being called, but the return value is just being dscarded. Putting the # causes it to be written in the response.
The RenderAction method writes the action directly to the view and returns void.
The Action method returns the action's contents but doesn't write anything to the view.
Writing #something will print the value of something to the page.
You cannot write #Html.RenderAction, since RenderAction doesn't return anything.
Writing Html.Action(...) (without #) calls the method normally, but doesn't do anything with its return value.
OK, Changing the way the it was called from _Layout.cshtml worked...
<div id="categories">
#Html.Action("Menu", "Nav");
</div>
It is important to note, that #Html.RenderAction DOES NOT work for me. I'd really love some explanation here, because right now, learning Razor is frustrating me as there is little documentation, and problems like these which should take minutes to resolve, are eating up way too much of my time.
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 });
}
Can't seem to get checkbox to be validate on client-side using asp.net mvc 2. Here is my code.
Model
[Serializable]
public class RegistrationModel
{
bool termsAndCondition = false;
[RequiredToBeTrue(ErrorMessage = "Need terms and service")]
public bool TermsAndConditions
{
get
{
return termsAndCondition;
}
set
{
termsAndCondition = value;
}
}
}
Custom Attribute
public class RequiredToBeTrueAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
return (value != null) && (value is bool) ? (bool)value : false;
}
}
View
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<RegistrationModel>" %>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm("Register", "Registration", new { area="Account", id = "openid_form", inRegistration = true }))
<%=Html.ValidationSummary(false) %>
blah blah blah
<div class="checkbox"><label><%= Html.CheckBoxFor(model => model.TermsAndConditions) %>I agree to the terms and conditions of use.</label></div>
<input type="submit" id="submit" name="submit" value="Join Now" />
<%
Html.ValidateFor(m => m.TermsAndConditions);
%>
<% } %>
I am trying to call Html.ValidateFor at the end to push up all error message at top of the page. However, the property "TermsAndConditions" is not getting validated on client side (works great on server side). This leads me to look at the the window.mvcClientValidationMetData method at that mvc push out and I saw the following:
{"FieldName":"TermsAndConditions","ReplaceValidationMessageContents":false,"ValidationMessageId":null,"ValidationRules":[]}
Which you can see that "ValidationRules" are empty meaning that it is trying to validate it but the error message wasn't push out to the client for some reason.
Any ideas? Any help is appreciated.
Seems like I need to do more digging first. Was hoping the new attribute will appear magically on the client side. Instead, have to write some customer javascript to wire it up. See phil hack's post for detail.
This article from Phil Haack, ASP.NET MVC 2 Custom Validation, should help point you in the right direction.
Basically you need to create your own DataAnnotationsModelValidator<RequiredToBeTrueAttribute> and then write some client side script to get it done.
HTHs,
Charles