make Html.Editorfor field readonly in mvc3 - asp.net-mvc-3

I am using this, an editor template (located in the Shared\EditorTemplates folder in my solution)
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%=Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), ViewData )%>
and this in my view
#Html.EditorFor(model => model.ModifiedDate)
how to make this field readonly in the view

<%= Html.EditorFor(x => x.ModifiedDate, new { #readonly = "readonly" }) %>
UPDATE:
OK, now that you sent me the sample project here are the issues:
You have a spelling mistake in the ~/Views/Shared/EditorTempletes folder. It should be ~/Views/Shared/EditorTemplates.
You editor template must be called DateTime.ascx and not a DateTime.aspx. And because of this the header must look like this (use <%# Control ... instead of <%# Page ...):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>"
%>
<%= Html.TextBox(
"",
(Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty),
ViewData
) %>

You can use:
#Html.DisplayFor()

Decorate the property with the [HiddenInput] Attribute from the System.Web.Mvc namespace.

I use to show read-only information this way:
#Html.DisplayFor(model => model.CadastradoEm, new { #class = "form-control" })
#Html.HiddenFor(model => model.CadastradoEm)
You need to include a hidden input in addition to the display text, cause DisplayFor() doesn't generate a control that posts back
;)

Related

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.

How to get model's field name in custom editor template

I'm building my first custom editor template for a text area control. My code so far is -
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%= Html.TextAreaFor( Model => Model , 2, 30,
new { #class = "html", #placeholder = ViewData.ModelMetadata.Watermark }) %>
It's not much so far, but it does work. But we need to add a character counter field to show remaining number of characters that the user can type in. I know how to do all the JavaScript to make this work.
So to keep naming system same, I'm going to add a control named ".charCounter" to display number of remaining characters left. My problem is that I cannot figure out the correct syntax to be able to retrieve the field name for the model.
The final version will look something like (JavaScript omitted) -
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%= Html.TextAreaFor( Model => Model , 2, 30,
new { #class = "html", #placeholder = ViewData.ModelMetadata.Watermark }) %>
<span class="xxx">Remaining characters -
<input readonly type="text" name="<fieldName>.charCounter" />
</span>
You could use ViewData.TemplateInfo.HtmlFieldPrefix, like this:
<input
readonly="readonly"
type="text"
name="<%= ViewData.TemplateInfo.HtmlFieldPrefix %>.charCounter"
/>
I ran into an issue where the PropertyName wasn't returning the Model prefix eg Contact.FirstName. I was able to have it return the HTML field Id using this:
#ViewData.TemplateInfo.GetFullHtmlFieldId("")
Returns:
Contact_FirstName
Respectively you can return the field name using:
#ViewData.TemplateInfo.GetFullHtmlFieldName("")
Returns:
Contact.FirstName
ViewData.ModelMetadata.PropertyName works nicely in MVC3.
In razor:
<input readonly="readonly" type="text" name="#ViewData.ModelMetadata.PropertyName">
Getting just the model name/Id (e.g BirthDate):
ViewData.ModelMetadata.PropertyName;
Getting the model name with prefixes for complex objects (e.g Identity.Person.BirthDate):
#Html.NameFor(m => Model);
or
ViewData.TemplateInfo.HtmlFieldPrefix;
Getting the model Id with prefixes for complex objects (e.g Identity_Person_BirthDate):
#Html.IdFor(m => Model)
or
#Html.IdForModel()

Why can't I use the ASP.NET MVC 3 Razor engine (with the new #-syntax) in a UserControl?

I am creating a UserControl that will read data from an XML file and populate a ListBox. I've open up the .ascx file and would like to use #foreach (etc..) but this isn't valid?
Can someone explain why this isn't possible? Or maybe confirm if UserControls are deprecated in MVC 3?
.ascx is WebForms. # is Razor, meaning that if you want to write #foreach(...) you need a Razor template: Foo.cshtml:
#model IEnumerable<AppName.Models.Foo>
#foreach (var item in Model)
{
...
}
And if you want WebForms user control Foo.ascx:
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<AppName.Models.Foo>>"
%>
<% foreach(var item in Model) { %>
...
<% } %>

dotnetopenauth and ajax forms

I'm trying implement an openId login with Google account together with ASP.NET MVC 2 framework and DotNetOpenAuth library.
The following code is used to render login button:
<% using (Html.BeginForm("LogOnPostAssertion", "Authentication", FormMethod.Post, new { target = "_top" }))
{ %>
<%= Html.AntiForgeryToken() %>
<%= Html.Hidden("ReturnUrl", "/", new { id = "ReturnUrl" }) %>
<%= Html.Hidden("openid_openidAuthData") %>
<%= Html.OpenIdSelector(this.Page, new SelectorButton[] {
new SelectorProviderButton("https://www.google.com/accounts/o8/id", AppHelper.ImageUrl("login/google.gif")),
new SelectorOpenIdButton(Url.Content("~/Content/google.gif"))
}) %>
<% } %>
</div>
</div>
<% var options = new OpenIdSelector();
options.DownloadYahooUILibrary = false;
%>
<%= Html.OpenIdSelectorScripts(this.Page, options, null) %>
This code works fine until I want to use AJAX. I don't want to reload the whole page after user was logged in. If I change Html.BeginForm with Ajax.BeginForm the authentication stops working. "LogOnPostAssertion" action is not called.
On my site the login form is opened in popup modal dialog. I want to verify user, close the dialog and refresh user status area using javascript. As example the process should be similar to the one as at http://shopping.com
Could it be because when you switched it to AJAX that you didn't preserve the POST HTTP method?
When I tried replacing the Html.BeginForm line with this one, it worked:
<% using (Ajax.BeginForm("LogOnPostAssertion", "Auth", new AjaxOptions { HttpMethod = "POST" })) { %>
By setting a breakpoint on the LogOnPostAssertion action, I saw that it did work. But the action itself would need to be adjusted to not send redirects but rather send whatever update script is appropriate.

MVC Multiple ViewPage items in aspx required

I need to pass in 2 objects to a page to access Model.NewsItems and Model.Links
(the first is a class of news item objects with heading, content etc and the Links are a set of strings for hyperlink depending on whether the system is up or down.
This is the page declaration
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<Tolling.Models.NewsItems>" %>
If I refer to Model.Items - I am fine.
However, if I refer to Model.HyperLink1, I am not.
How can you pass in multiple objects into the page?
I have tried importing both namespaces without success - i.e.
<%# Import Namespace="Tolling.Models.News" %>
<%# Import Namespace="Tolling.Models.HyperLinks" %>
Create a ViewModel class that contains both of your model collections and then pass that too the view:
Sample Controller:
var myNewModel = new MyNewModel()
{
NewsItems = new List<NewItem>(),
HyperLinks = new List<HyperLink>()
}
return View(myNewModel);
View page declaration:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MyNewModel>" %>
Then you can access them in your view with your new ViewModels properties:
<%= Model.NewsItems %>
<%= Model.Hyperlinks %>
You can pass extra data into the View by using ViewData, TempData, Session or Cache. I'd suggest you use ViewData. As described by MSDN:
Gets or sets a dictionary that
contains data to pass between the
controller and the view.

Resources