Using a edit template without using Html.EditorFor() - asp.net-mvc

I have a date time picker combination in a edit template that can be used like Html.EditorFor(x => x.ETA) but now I want to use the same template somewhere where I don't have a model that contains a DateTime property. So I tried Html.Editor("DateWithTime", "Arrival") which uses the correct template, but doesn't assign a value to ViewData.ModelMetadata.PropertyName which is something that my template relies on. It sets the id of the textbox which is obviously important.
Is there a way to render the template and assign a id value to the ViewData.ModelMetadata.PropertyName so I can re-use the logic in the template instead of having to copy it?

Maybe use ViewData.TemplateInfo.HtmlFieldPrefix instead of ViewData.ModelMetadata.PropertyName.
I am not sure but I thought that HtmlFieldPrefix an PropertyName have the same value as long as you do not iterate a collection.
You can modify the HtmlFieldPrefix property with the htmlFieldName parameter from Html.Editor.

You can use the UIHint in your model. give it the name of the template you want to use
[UIHint("DateWithTime")]
You still use EditorFor with this.

Related

Bind Value with DropDownListFor [duplicate]

I am working on an ASP.NET MVC-4 web application. I'm defining the following inside my action method to build a SelectList:
ViewBag.CustomerID = new SelectList(db.CustomerSyncs, "CustomerID", "Name");
Then I am rendering my DropDownListFor as follow inside my View:
#Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, "please select")
As shown I am naming the ViewBag property to be equal to the Model property name which is CustomerID. From my own testing, defining the same name didn't cause any problem or conflict but should I avoid this ?
You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property).
When using #Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData, and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).
When using #Html.DropDownList("CustomerId", ....), no data-val-* attributes will be generated and you will not get any client side validation
Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly.
There is not harm to use it. You will not get any error. but best practice is to bind model property.

How to show the value of model in Kendo Custom Editor Template?

I'm using a scheduler of Kendo UI for MVC. I created a Custom Editor Template. It works fine. When click the schedule, it pops a windows and show the info.
I added some properties in the model, the value passed to the editor template. Now, the question is:
How can I show the added properties (just as value, and I do not want to change it) in the editor template popup?
I found that if I use a textbox:
#(Html.TextBoxFor(model => model.Role, new { #class = "k-textbox" }))
It shows a textbox and shows the correct value of Role. However, if I use
<div>#(Model.Role)</div>
It shows blank, just as the value is NULL.
I actually want to show several added properties as a sentence, i.e. I added Role and UserName and I ant to show something like:
UserNameValue has Role of RoleValue
Anyone knows how to do it?
I use this as sample in the code:
http://www.telerik.com/support/code-library/custom-editor
Thanks
Your solution is to put this line because the editor template is binded by mvvm
<div data-bind="text: Role"></div>
Docs
In the code: model => model.Role model is just an alias, not an actual object. You could replace it with m => m.Role and it would function the same.
When you write #Model in your view you are using the object of ContractViewModel which is passed from Controller action, if it is not passed from View it can be null and accessing any property of Model can throw Null Reference Exception and writing Model.Contractors you basically mean ContractViewModel.Contractors
See this post: mvc uppercase Model vs lowercase model

Confused about Usage of LabelFor() html helper in MVC 2.0

I am working on an MVC 2.0 C# web Applciation. In one of my form, i am using LabelFor() html helper.
I am using the following syntax:
<%=Html.LabelFor(model=>model.Addedon)%>
Here, for this label i would like to associate a initial value that is DateTime.Now
I tried some thing like this:
<%=Html.LabelFor(model=>model.Addedon,new{value=DateTime.Now})%>
But, i am getting an error saying that there is no over load for this helper taking two arguments.Please help
UPDATED:
The form is create form/ add form which makes an insert operation. So, i am building a model and updating that model to the database.
In that model, i have a field called createdby. So, i need to associate this value with the username logged in and doing the insert operation.
So, how to associate this username value with the model field and i need to display as label so that it will be read only field.
Hope this makes clear..
LabelFor is only for, you guessed it, rendering a <label> element.
It also uses the [Display] and [DisplayName] attributes, so you can have a strongly-typed label with custom name.
What you're after is probably this:
<div>
<%= Html.LabelFor(model => model.Addeon) %>
</div>
<div>
<%= Html.DisplayFor(model => model.Addeon) %>
</div>
So the LabelFor will generate the property name description (e.g. 'Addeon'), while the DisplayFor will render the property value. DisplayFor can use the [DisplayFormat] attribute if you need custom formatting. You can set the default property value in the view model's constructor:
public class ViewModel
{
[Display(Name = "My awesome date")]
public DateTime Addeon {get;set;}
public ViewModel()
{
Addeon = DateTime.Now;
}
}
[EDIT]
Actually, your edit would make for a good second question instead of putting it here. Anyway, in your situation I'd create a dedicated view model that would hold the properties you need (e.g. user name) and would be filled in controller. Everything else would be conceptually the same - view would bind to the view model.

MVC #Html.Display()

I have something like:
<input type="text" name="TerrMng" id="TerrMng"/>
in HTML. What is the equivalent of the above using #Html.Display?
I tried using: #Html.Display("TerrMng", TerrMng)
but was not successful. Note that I like to use #Html.Display but not sure how to translate the ID value so that it shows up.
The Display method is not for creating input boxes. You'd want to use:
#Html.TextBoxFor(m => m.TerrMng);
or the templated helper method:
#Html.EditorFor(m => m.TerrMng);
I'm assuming that you want to use modelbinding. If not, if you really just want to use a helper to simply make an input tag, use:
#Html.TextBox("TerrMng");
This would be sent to the client:
<input id="TerrMng" type="text" value="" name="TerrMng">
The first 2 methods above would result in the exact same html, if model.TerrMng was "" or String.Empty. If for some reason you don't want the value attribute, you'll need to type it out yourself.
This should do the trick if you are just wanting to display the data and not allow the user to edit the information.
#Html.DisplayFor(m => m.TerrMng);
Edit:
what-is-the-html-displayfor-syntax-for is another question on stackoverflow that may give you some more guidance.
Edit:
TerrMng does not exist on PageLoad so you cannot use the Html.Display in that way. You need to create it and fill its value with the value received from the jQuery. In this case where you would have to do the following:
HTML
#Html.Display("TerrMng"); // This creates the label with an id of TerrMng
jQuery
$("#TerrMng").val(TerrMng); // This puts the value of the javascript variable into the label
You could try something based on this. This is not exact but you could get some idea.
#Html.TextBoxFor(yourmodel => model.yourModelFieldname, null)
#Html.Display() is used instead of #Html.DisplayFor() when your model is not known at compile time, or if you prefer to work with strings, rather than with strong types. For example, these 2 are equivalents (given that your model is some class):
#Html.DisplayFor(m => m.MyProperty)
and
#Html.Display("MyProperty")
But the additional cool feature of the Display() method is that it can also do the lookup in the ViewData, and not just in your Model class. For example, here is a way to display the HTML for the property on a random object, given that we know it has a property named "Blah" (the type of the object doesn't really matter):
#{ ViewData["itsawonderfullife"] = SomeObject; }
<div>#Html.Display("itsawonderfullife.Blah")</div>
This way, we are telling HtmlHelper to look into the ViewData, instead of our Model, and to display the property Blah of a given SomeObject.

ASP.Net MVC, Dynamic Property and EditorFor/LabelFor

I am using MVC 3 w/ Razor and using the new dynamic ViewBag property. I would like to use the ViewBag property with the EditorFor/LabelFor Html helpers but can't figure out the syntax.
The View does have a #model set, but the object I am trying to use is not part of that model. I am aware I can create a ViewModel but that is not what I am after.
Can anyone help?
Controller:
var myModel= _repo.GetModel(id);
var newComment = new Comment();
ViewBag.NewComment = newComment;
return View(myModel);
View:
#model Models.MyModel
#(Html.EditorFor(ViewBag.NewComment.Comment))
I haven't tried it, but this should work I think.
#(EditorFor(m => ViewBag.NewComment)
It is possible to use a Linq-to-SQL syntax, but use a completely different object on the right side.
Not knowing what your Comment Model looks like, my gut reaction would be to just do:
#Html.EditorFor(ViewBag.NewComment)
However, because ViewBag is dynamic, you may need to cast NewComment before you use it, in order to get the EditorFor magic.
#Html.EditorFor(ViewBag.NewComment as Comment)
Update
Strike that, EditorFor can only accept an Expression as a parameter, and that Expression must return a property of the page model. I don't think EditorFor or EditorForModel are going to be of any use to you if you don't want to use a ViewModel. Have you considered switching the roles of whatever it is you're using the Model for, with that of the ViewBag?
If for some reason I need to use ViewData to pass the model into my view I do the following to allow for the Html.DisplayFor() helpers.
In the views code block I cast the ViewData model object to its underlying type
var newCommentModel = ( NewComment )ViewBag.NewComment;
Then I assign the following expression to the helper using the strong-typed reference
#Html.DisplayFor( model => newCommentModel )
The expression tree now contains a strongly-typed model and the DisplayTemplate is correctly displayed.

Resources