how to pass default value to textbox dynamically? - asp.net-mvc-3

mvc3 razor- i have a bellow model in my web app:
public class mymodel{
[Display(Name = "name")]
public string Name { get; set; }
}
when we use
#Html.LabelFor(m => m.Name)
it use display "name" ,for example upper of our text box to show user this filed is for entering your name.
how can i use display name in text box value?
i test it but value is empty i want to get value from my model from [Display(Name = "name")]
#Html.TextBoxFor(m => m.Name, new {#Value = #Html.ValueFor(m => m.Name)})

#Html.TextBoxFor(m => m.Name, new {Value = Html.DisplayNameFor(m => m.Name)})
EDIT: If you need to re-display the form and preserve the value that the user entered, then you might want to either use Darin's approach, or do something like this:
#Html.TextBoxFor(m => m.Name, new { Value = (string.IsNullOrWhiteSpace(Model.Name) ? Html.DisplayNameFor(x => x.Name).ToHtmlString() : Model.Name) })

In the controller action rendering this view you could set the Name property of your view model:
public ActionResult Index()
{
var model = new MyViewModel();
model.Name = ModelMetadata.FromLambdaExpression<MyViewModel, string>(x => x.Name, new ViewDataDictionary<MyViewModel>(model)).DisplayName;
return View(model);
}
and in your view:
#Html.LabelFor(x => x.Name)
#Html.EditorFor(x => x.Name)

Related

Telerik.UI.for.AspNet.Core in MVC Cannot display data in Grid from a DB context

I think I'm close. Its not throwing any errors but its also not displaying any data... Im just trying to get it to display a list of Company Names and Company IDs from my TblCompanyInfo table.
This is my controller:
public async Task<IActionResult> Index()
{
var apptReminderContext = _context.TblCompanyInfos.Include(t => t.AcctType).Include(t => t.CompanyStatus).Include(t => t.OnHoldReason);
return View(await apptReminderContext.ToListAsync());
//return View();
}
public JsonResult Products_Read([DataSourceRequest] DataSourceRequest request)
{
DataSourceResult result = _context.TblCompanyInfos.ToDataSourceResult(request,
model => new TblCompanyInfo
{
CompanyId = model.CompanyId,
CompanyName = model.CompanyName
});
return Json(result);
}
and my view...
#model IEnumerable<AppointmentRemindersNetCoreMVC.Models.TblCompanyInfo>
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
#using AppointmentRemindersNetCoreMVC.Data
#using Kendo.Mvc.UI
#addTagHelper *, Kendo.Mvc
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#Html.AntiForgeryToken()
#(Html.Kendo().Grid<AppointmentRemindersNetCoreMVC.Models.TblCompanyInfo>()
.Name("grid")
.DataSource(dataSource => dataSource.Ajax()
.Read(read => read.Action("Products_Read", "Company"))
.PageSize(20)
//.ServerOperation(false)
//.Model(model => model.Id(c => c.CompanyId))
//.Read("Products_Read", "Company")
//.Read(read => read.Action("Products_Read", "Company"))
.Update("UpdateCustomer", "Home")
.Create("InsertCustomer", "Home")
.Destroy("DeleteCustomer", "Home"))
.Columns(columns =>
{
columns.Bound(product => product.CompanyName);
columns.Bound(product => product.CompanyId);
})
.Pageable()
.Sortable()
)
Also I know that the Products_Read function is being called by the view and I also know that the "result" contains 32 rows of data. However, nothing is displayed in the grid.
Figured it out! Turns out that json camelcases the return string so the model properties did not match what was returned by json. The solution was to add this line to the Startup.cs file.
services.AddControllers()
.AddJsonOptions(options =>
options.JsonSerializerOptions.PropertyNamingPolicy = null);

How to get the MVC contrib grid custom colum working with aspx

I am using the MVC Contrib Grid for rendering, sorting and filtering my data grid, but I am having problems now that it has been upgraded for MVC3 and Razor. The Custom method in my columns collection does not work for aspx pages , and the columns Action method is now obsolete.
I use grids action method to render my columns like this in MVC 2:
...
<% Html.Grid(Model).Columns(column => {
column.For(x => x.Id);
column.For(x => x.Name);
column.For(x => x.Email);
column.For(x => x.DateOfBirth);
column.For("View User").Named("Tools").Action(x => { %>
<td>
<%= Html.ActionLink("View", "View", new { id = p.Id })%>
<%= Html.ActionLink("Edit ", "Edit", new { id = p.Id })%>
//Snip as there are too many tools :-)
//.....
<%= Html.ActionLink("Delete", "Delete", new { id = p.Id })%>
</td>
<% });
...
Now with the latest version there is a Custom method that replaces the obsolete Action method. I looked at how it can be done in here, which basically works for me now, but I loose all my helpers in the aspx view (url, etc), and now need to render my contents in another method in my model like below:
...
<% Html.Grid(Model).Columns(column => {
column.For(x => x.Id);
column.For(x => x.Name);
column.For(x => x.Email);
column.For(x => x.DateOfBirth);
//the new custom column
column.Custom(Model.ToolsRenderer);
<% });
...
The grid model method below called ToolsRenderer is used to render my html string.
public UserManagementViewModel : BaseModel {
//..snip
//
public object ToolsRenderer(Client client)
{
List<string> links = new List<string>();
var editLink = new TagBuilder("a");
// here is my biggest problem, before Html.ActionLink used to make
// sure that I don't have any missing links or help me if i need to
// refactor an action / controller name :-(
editLink.Attributes["href"] = GetEditUserLink(client, HttpContext.Current.Request.Url.AbsoluteUri);
editLink.SetInnerText("edit");
links.Add(editLink.ToString());
...
...lots of links to be generated here
...
return MvcHtmlString.Create(string.join(" |", links))
}
//..snip
}
This works for now, but is there a way to get my aspx page working like the razor views like below?
#Html.Grid(Model).Columns(column =>
{
column.For(x => x.Id).
column.For(x => x.Name);
column.Custom(#<td><a href='#Html.Actionlink("edit","user",new {id})' alt="#item.email"/><a></td>)
})
I want to say something like:
...
column.Custom(%><td><a href='<%=Html.Actionlink("edit","user",new {id})%>' alt="<%=item.email%>"/><a></td><%)
...
Finally managed to find a work around with some help and digging, and instead of using the custom column, use column.for and push in the Html.Partial. Something like the code below.
<% Html.Grid(Model).Columns(column => {
column.For(x => x.Id);
column.For(x => x.Name);
column.For(x => x.Email);
column.For(x => x.DateOfBirth);
// could use RenderPartial() to
column.For(x =>Html.Partial("UserActionColumn", x));
<% });
For Razor case #helper can be used for custom fields.
For example:
column.For(r => Status(r.Status)).Encode(false).Named("Status");
#helper Status(string value)
{
if (value == RequestStatus.Pending)
{
<span class="label label-info">#value</span>
}
...
}
Complementing the other answers, if you want to sort by that custom column, don't forget to add a SortColumnName. If you don't do this, the grid will use the Named argument as the column name, but Named is also used to give a title to the column. I just got a headache because my column name didn't match the title:
column.For(c => "custom text").Named("Column Name").SortColumnName("ColumnName");

Telerik MVC - Numeric textbox in grid editor

In my editor for insert telerik show only common textbox (not integer,decimal etc).
this is my view:
#(Html.Telerik().Grid <GamePlayer2>(Model).Name("za11").DataKeys(keys => keys.Add(c => c.Id))
.ToolBar(commands => commands.Insert()
.ButtonType(GridButtonType.ImageAndText))
.DataBinding(dataBinding => dataBinding.Server()
.Insert("PlayerAdd", "Player", new { })
.Update("PlayerUpdate", "Player", new { })
.Delete("PlayerDelete", "Player", new { })
)
.Columns(columns =>
{
columns.Bound(b => b.Name);
columns.Bound(b => b.Price);
columns.Command(commands =>
{
commands.Edit();
commands.Delete();
}).Width(200);
})
.Editable(editing => editing.Mode(GridEditMode.PopUp)))
model:
public class GamePlayer2
{
public int Id { get; set; }
public string Name { get; set; }
[DataType(DataType.Currency)]
public decimal Price{ get; set; }
}
Scripts are registered on _Layout. Where is a problem? Why currency(integer,date etc) textbox won't display for fields?
Make sure you have added the EditorTemplates under the Shared/EditorTemplates folder. Basically they are automatically added if you have used the wizard to create your project. If not create a demo project and copy-paste them from there.

MVCContrib Grid - Show carriage returns

How do you show carriage returns inside a MVCContrib Grid? I've tried replacing the returns with "<br>", however that is actually showing a <br> in my display "test<br>test"
<div id="noteList">
#Html.Grid(Model).Columns(column => {
column.For(x => x.TimeStamp);
column.For(x => x.UserName);
column.For(x => x.Note.Replace("\r\n","\"<br>\"")).Named("Note");
}).Attributes(Style => "text-aligh: center", #Class => "linkGrid")
</div>
Is there a way to get the browser to render the original return's "\r\n"?
You could use a custom column:
column.Custom(item => #item.Note.Replace("\r\n", "<br/>")).Named("Note");
But a safer and IMHO a more robust solution would be to use a custom HTML helper:
public static class HtmlExtensions
{
public static IHtmlString FormatNote(this HtmlHelper html, string note)
{
if (string.IsNullOrEmpty(note))
{
return MvcHtmlString.Empty;
}
var lines = note.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
return MvcHtmlString.Create(string.Join("<br/>", lines.Select(x => html.Encode(x))));
}
}
and then:
column.Custom(item => Html.FormatNote(item.Note)).Named("Note");

Server-side Validation using MVC 3

I'm building an ASP.NET MVC3 app. I have 2 views;
List item contains a grid
details view consists of a drop down list (combobox)
I have a requirement to alert the user at the details view when they try to select item was previously selected in the list view. In other words, the grid should contain unique items
What is the best way to implement a server-side business logic validation?
Model:
public class AllocatedResource
{
public virtual Project Project { get; set; }
public virtual DateTime StartDate { get; set; }
public virtual DateTime EndDate { get; set; }
}
List View:
#(Html.Telerik().Grid(Model.AllocatedResources)
.Name("gridAllocatedProject")
.DataKeys(keys =>{keys.Add(p => p.Id);})
.Columns(columns =>
{
columns.Bound(p => p.Id).Visible(false);
columns.Bound(p => p.Project.Name);
columns.Bound(p => p.Project.ProjectManager).Title("Project Manager");
columns.Bound(p => p.StartDate).Width(80).Format("{0:d}");
columns.Bound(p => p.EndDate).Width(80).Format("{0:d}");
})
Details View:
#Html.Label("Project: ")
#(Html.Telerik().ComboBox().Name("Project")
.BindTo(new SelectList(Model.AllProjects, "Id", "Name"))
.Value(Model.AllocatedResource.Project.Id.ToString()))
#Html.Label("Start Date: ")
#(Html.Telerik().DatePicker().Name("StartDate")
.Value(Model.AllocatedResource.StartDate))
#Html.Label("End Date: ")
#(Html.Telerik().DatePicker().Name("EndDate")
.Value(Model.AllocatedResource.EndDate))

Resources