I'm going to bind data to a label using MVC4,But it's not success..Data come to model.
Here is my code.
<div class="newclass">
#Html.LabelFor(m => m.NewsTeam.NewsMgr, new { style = "width:100%", #class = "newcssval" })
</div>
Try like this:
#Html.LabelFor(m => Model.NewsTeam.NewsMgr)
or use DisplayFor
#Html.DisplayFor(m => m.NewsTeam.NewsMgr)
Hope it helps
This will only give you the name of the field (or it's display value from the class). I suspect what you need is the following.
#Html.TextBoxFor(m => m.NewsTeam.NewsMgr,
new { #class = "newcssval", #readonly = true })
This will give you a read-only text box wuth the content of your model data.
Hope that helps.
If your intent is to simply show the value of the property, use the Display or DisplayFor helper:
#Html.DisplayFor(m => m.NewsTeam.NewsMgr)
Or, forget the helper entirely:
#Model.NewsTeam.NewsMgr
If the property contains HTML, you'll need to use the Raw helper:
#Html.Raw(Model.NewsTeam.NewsMgr)
Use this,
#Model.NewsTeam.NewsMgr
It will just show the value of property as label
Or Use,
#Html.DisplayFor(m => m.NewsTeam.NewsMgr)
Related
I'm working with a Kendo Grid that shows a modal when editing or adding a row. I'm seeking to modify the modal and add another dropdown list to it. The one thing I'm totally confused about at the moment is that the cshtml for the modal refers to the ViewBag to provide the source data for the dropdownlists, but I can't find anywhere in the entire solution where any code (anywhere) populates the ViewBag with the properties the modal uses.
Before I started modifying, the cshtml had:
#Html.Kendo().DropDownListFor(model => model.Status).BindTo(ViewBag.Statuses).DataTextField("Name").DataValueField("Value").OptionLabel("Please Select")
^^^^^^^^^^^^^^^^
The debugger says this is valid; the ViewBag does contain a .Statuses and it is loaded with data, but I've no idea how this thing came to be in the ViewBag. The only place the controller refers to the viewbag is in setting the .Title
Here's cshtml for the modal:
#model ModalModel
#Html.HiddenFor(model => model.Id)
<!-- this is the new one -->
<div class="editor-group">
<div class="editor-label">
#Html.LabelFor(model => model.ProjectId)
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.ProjectId).BindTo(ViewBag.ProjectId_Data).OptionLabel("Please Select")
#Html.ValidationMessageFor(model => model.ProjectId)
</div>
</div>
<!-- existing one. Needs DataTextField and DataValueField because model.Statuses is not an IEnumerable<SelectListItem>, its a custom collection of c# enum name/value representation -->
<div class="editor-group">
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.Status).BindTo(ViewBag.Statuses).DataTextField("Name").DataValueField("Value").OptionLabel("Please Select")
#Html.ValidationMessageFor(model => model.Status)
</div>
</div>
Here's a snip of the cshtml for the main grid and some periphery stuff:
#model GridModel
<h3>#ViewBag.Title</h3>
#{
var projectListItems = Model.Projects.Select(e => new SelectListItem { Value = e.Id.ToString(), Text = e.Name });
var activityListItems = Model.Activities.Select(e => new SelectListItem { Value = e.Id.ToString(), Text = e.PrivateName });
}
#(Html.Kendo().Grid<UsageModel>()
.Name("MainGrid")
.Columns(cfg =>
{
cfg.Bound(e => e.DateUsed).ClientTemplate("#= kendo.toString(DateUsed, \"d\") #");
cfg.ForeignKey(e => e.ProjectId, projectListItems, "Value", "Text").Title("Project name").Width(150);
cfg.ForeignKey(e => e.ActivityId, activityListItems, "Value", "Text").Title("Activity name").Width(150);
cfg.ForeignKey(e => e.Status, Model.Statuses, "Value", "Name");
cfg.Command(cmd => { cmd.Edit(); cmd.Destroy().HtmlAttributes(new { style = "visibility:hidden" }); }).Width(80);
})
.Pageable()
...
The 4 items in the ViewBag are:
ProjectId_Data (IEnumerable<SelectListItem>)
ActivityId_Data (IEnumerable<SelectListItem>)
Status_Data (IEnumerable<SelectListItem>)
Statuses (IEnumerable<a custom internal type used for expanding enums into name/value strings>)
Am I correct in assuming that Kendo added these things to the viewbag as part of the data binding process on the main grid? The rendering of the grid to page occurs before the processing of the modal..
Please give (IEnumerable) inside BindTo() for casting and try
#using Kendo.Mvc.UI
#using System.Collections
#Html.Kendo().DropDownListFor(model => model.Status).BindTo((IEnumerable)ViewBag.Statuses).DataTextField("Name").DataValueField("Value").OptionLabel("Please Select")
I have just created an MVC project and my view looks like this
{
#model Models.LeadModels
ViewBag.Title = "Add a Lead";
}
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
<p>#ViewBag.SaveResult</p>
#using (Html.BeginForm("Add", "Lead"))
{
<p>#Html.LabelFor(m => m.FirstName)
#Html.TextBoxFor(m => m.FirstName)</p>
<p>#Html.LabelFor(m => m.LastName)
#Html.TextBoxFor(m => m.LastName)</p>
<p>#Html.LabelFor(m => m.Company)
#Html.TextBoxFor(m => m.Company)</p>
<p>#Html.LabelFor(m => m.Province)
#Html.TextBoxFor(m => m.Province)</p>
<p>#Html.LabelFor(m => m.Telephone)
#Html.TextBoxFor(m => m.Telephone)</p>
<p>#Html.LabelFor(m => m.EmailAddress)
#Html.TextBoxFor(m => m.EmailAddress)</p>
<p>#Html.LabelFor(m => m.LeadStatus)
#Html.TextBoxFor(m => m.LeadStatus)</p>
<p><input type="submit" value="Add Lead" /></p>
}
When this is rendered the labels are the same as my model properties, as in the text says "FirstName"
Questions.
Is there a way to put in a different label (First Name instead of FirstName) using a HTML Helper method?
Are there any neat stuff/tricks we can do to change the display? Such as set the labels to be a fixed width so they all line up?
Is there a way to use a HTML Helper method to output the submit button? Or do I need to manually write the HTML like I am doing?
Is there a way to put in a different label (First Name instead of
FirstName) using a HTML Helper method?
You can use Display attribute data annotation on your property name
public class LeadModels
{
[Display(Name = "First name")]
public string FirstName { set; get; }
}
LabelFor helper method will render the value you provided for the Name attribute
Are there any neat stuff/tricks we can do to change the display? Such
as set the labels to be a fixed width so they all line up?
You can use your css classes style the content. You may also consider using bootstrap css classes which does the alignment in a neat way
Is there a way to use a HTML Helper method to output the submit
button? Or do I need to manually write the HTML like I am doing?
No. There is no helper methods for that. You should write your html tag for the button.
Also, in the asp.net core version, tag helpers are available which allows us to write more HTML style code instead of calling the C# methods in view.
I have a question that feels like it should be easy to answer, but I am not sure where to go with it.
I have several cshtml pages that take different models. But, each of these models has a common property, called WebSiteSK, and the same razor and Kendo UI code that handles that property in each cshtml file. What I want to do is extract this common razor and Kendo UI into an EditerTemplate.
So, I have one cshtml page that takes a Model, which I'll call ModelA. Then, another that takes another model, called ModelB. Both ModelA and ModelB have an integer property called WebSiteSK, which the code that I want extract into an editor template receives.
Here is the code that I want to centralize in an editor template:
<script type="text/x-kendo-tmpl" id="site-droplist-template">
<span>#: data.WebSiteSK # - </span>
<span><b>#: data.SiteName # </b> - </span>
<span>#: data.EnvironmentNK #</span>
<br />
<span>#: data.SiteUrl #</span>
</script>
<div>
#Html.LabelFor(model => model.WebSiteSK, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#(Html.Kendo().DropDownList()
.Name("WebSiteSK_Target")
.DataTextField("SiteName")
.DataValueField("WebSiteSK")
.DataSource(d => d.Read("GetWebSiteList", "Site"))
.Height(300)
.TemplateId("site-droplist-template")
.Filter("contains")
.OptionLabel("Select a site")
.Events(d =>
{
d.DataBound("onSiteBound");
d.Change("onSiteChange");
})
)
#Html.ValidationMessageFor(model => model.WebSiteSK, string.Empty, new { #class = "text-danger" })
</div>
</div>
Does that make sense? Can anyone help me do this?
You can create a base class that contains only the property 'WebSiteSK'. All models that have have this property then should inherit from this base class. Then you can create a partial view '_WebSiteSK' with the code that you want to reuse.
Your models:
public class MyModel : WebSiteSKBaseClass
The partial view must be typed with the base class
#model MyProject.Models.WebSiteSKBaseClass
Finally you can replace the replicated code in all views with:
#Html.Partial("_WebSiteSK")
I have three dropdownlistfor in a loop that do not show the correct value from the DB. They always default to the first entry. I have checked and double checked the DB and verified that it should be the second one in the list. The list is also created correctly. What am I missing?
#foreach (CustomerMeasurementProfile oProfile in Model.Customer.CustomerMeasurementProfiles.Where(m => m.DeletedDate == null))
{
<div class="valuesforoneprofile form-group form-group-tight col-md-2">
<div class="col-md-11" >
#Html.Hidden(string.Format("Customer.CustomerMeasurementProfiles[{0}].Id", i), oProfile.Id)
#Html.Hidden(string.Format("Customer.CustomerMeasurementProfiles[{0}].CustomerId", i), oProfile.CustomerId)
#Html.TextBox(string.Format("Customer.CustomerMeasurementProfiles[{0}].Name", i), oProfile.Name, new { #class = "form-control input-sm" })
</div>
<div class="col-md-11" style="text-align:center">
#Html.CheckBox(string.Format("DeleteProfiles[{0}]", i), Model.DeleteProfiles[i])
</div>
<div class="col-md-11" style="padding-top:4px;">
#Html.DropDownListFor(m => oProfile.BodyTypeShoulderId, new SelectList(Model.BodyTypeShoulders, "Id", "Name"), new { #class = "form-control input-sm-select" })
</div>
<div class="col-md-11" style="padding-top:4px;">
#Html.DropDownListFor(m => oProfile.BodyTypePostureId, new SelectList(Model.BodyTypePosture, "Id", "Name"), new { #class = "form-control input-sm-select" })
</div>
<div class="col-md-11" style="padding-top:4px;">
#Html.DropDownListFor(m => oProfile.BodyTypeChestId, new SelectList(Model.BodyTypeChest, "Id", "Name"), new { #class = "form-control input-sm-select" })
</div>
If you want to set the selected value that is coming in Model. You need to do it like this:
#Html.DropDownListFor(m => oProfile.BodyTypeShoulderId,
new SelectList(Model.BodyTypeShoulders,
"Id",
"Name",
oProfile.BodyTypeShoulderId),
new { #class = "form-control input-sm-select" })
The above code will set the dropdown selected value to whatever is in the current Model object BodyTypeShoulderId
The first argument of DropDownListFor tells that on form post drop down selected value will be mapped with the Model property which is set there (we are passing m => oProfile.BodyTypeShoulderId) but this not sets selected Value.
For setting selected value you have to pass SelectList fourth parameter using this overload of SelectList class which is object selectedValue
Unfortunately #Html.DropDownListFor() behaves a little differently than other helpers when rendering controls in a loop. For a single object
#Html.DropDownListFor(m => oProfile.BodyTypeShoulderId, new SelectList(Model.BodyTypeShoulders, "Id", "Name"))
would work fine (if the value of BodyTypeShoulderId matches the value of one of the options, then that option would be selected). Ehsan has shown a work around when using it in a loop, however you have a few other issues in you code, not the least is that many of your properties will not post back correctly to a collection because your using a foreach loop rather than a for loop (which is generating duplicate name and id attributes). Your also generating a new SelectList in each iteration of the loop which is not very efficient.
You can solve both these and the dropdown selection issue by using an EditorTemplate. Assuming property CustomerMeasurementProfiles is typeof CustomerMeasurementProfiles, then
CustomerMeasurementProfiles.cshtml (add this to Views/Shared/EditorTemplates or Views/YourController/EditorTemplates)
#model CustomerMeasurementProfiles
#Html.HiddenFor(m => m.ID)
#Html.HiddenFor(m => m.CustomerId)
....
#Html.DropDownListFor(m => m.BodyTypeShoulderId, (SelectList)ViewData["shoulders"])
....
In the view model, add properties for the SelectList's and filtered collection of the items to display
IEnumerable<CustomerMeasurementProfiles> ActiveCustomerMeasurementProfiles { get; set; }
public SelectList BodyTypeShoulderList { get; set; }
....
and assign those values in the controller
Then in the main view
#using (Html.BeginForm())
{
...
#Html.EditorFor(m => m.ActiveCustomerMeasurementProfiles, new { shoulders = Model.BodyTypeShoulderList })
...
Using #Html.EditorFor() with a collection will correctly name the controls (and correctly select the right options) and on post back, ActiveCustomerMeasurementProfiles will now be correctly populated with all its properties.
I have a collection of objects that I'm trying to display, however the span generated by the ValidationMessageFor does not include all the validation attributes:
<span class="field-validation-error">This field is required</span>
instead of:
<span class="field-validation-error" data-valmsg-replace="true" data-valmsg-for="Questions[0].SingleAnswer"></span>
This is how I'm generating the html:
<fieldset id="dr_profileUpdates">
#Html.EditorFor(model => model.Questions)
</fieldset>
And here is my editor template:
#Html.ValidationMessageFor(model => model.SingleAnswer)
#Html.TextBoxFor(model => model.SingleAnswer, new { #class = "textBoxDefault" })
The validation works, however the span does not dissapear after filling out the textbox and focusing out of it - I would assume this is because the span does not get generated correctly
Any help is appreciated.
EDIT: Actually it appears that after posting back to the server and returning the partial view (assuming the ModelState is invalid), those attributes do not get generated again - it only seems to affect the ValidationMessage. Any ideas?
Thanks,
Try add on top of your razor file
#{
Html.EnableUnobtrusiveJavaScript();
}