ASP.NET MVC 4 - Set input value using #Html.EditorFor - asp.net-mvc

Currently i have this field on a form:
#Html.EditorFor(model => model.AmountDecimal,
new { htmlAttributes = new { #class = "form-control" } })
But:
a) i want it to have the value "100" predefined
b) don't want it to be editable
I know how to do it in raw HTML but i need it to be in razor.
Thanks

It would make sense to set this value e.g. in the constructor of your model or in the controller before you call your view
public ActionResult MyAction()
{
var model = new MyViewModel
{
AmountDecimal= 100
};
return View(model);
}
But if you really like to do it in razor, you may use HiddenFor
#Html.HiddenFor(model => model.AmountDecimal, new { #Value = "100" });
<input type="text" name = "dummy" class="form-control" value="100" readonly/>
Keep in mind to never trust a user input ;)

I think your are loooking for something like this:
#Html.EditorFor(model => model.AmountDecimal,
new { htmlAttributes = new { #class = "form-control", #Value = "100", #readonly = "readonly"} })

Related

Custom EditorFor Template and htmlAttributes

I'm trying to use EditorFor custom templates.
I want to create a Int32 and decimal templates to render the inputs with some validations.
This is what I'm trying
#model int?
#Html.TextBoxFor(model => model, null, new { #type="text", #oninput = "this.value=this.value.replace(/[^0-9]/g,'')" } )
And I call it like
#Html.EditorFor(x => x.ExampleIntField)
It renders an <input type="text", oninput="this.value=this.value.replace(/[^0-9]/g,'')"
To here everything works, but when I try to pass extra htmlAttributes like readonly I don't understand how I must receive it in EditorFor template.
Example
#Html.EditorFor(x => x.ExampleIntField, new { htmlAttributes = new { #readonly = "readonly" } } )
I tried this I got the exact same <input type="text", oninput="this.value=this.value.replace(/[^0-9]/g,'')" rendered without readonly attribute
You are using the overload of EditorFor() that passes the object as additionalViewData. You can read that within the template from the ViewDataDictionary
#model int?
#{ var attributes = ViewData["htmlAttributes"]; } // returns { #readonly = "readonly" }
which you could then merge with your existing attributes and use in the TextBoxFor() method.
#{
var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attributes);
htmlAttributes.Add("oninput", "this.value=this.value.replace(/[^0-9]/g,'')";
}
#Html.TextBoxFor(model => model, htmlAttributes)
Note that TextBoxFor() generates type="text" so there is no need to add it again. In addition, you do not need the leading # unless its a reserved keyword (for example #class = "...")

Remove MVC 5 EditorTemplate additional ID

I am using this Editor Template for Dropdownlist with ViewBag/ViewData of same property Name
#model System.String
#*
For Using this Editor Template
- There should be a viewbag/viewdata (type SelectList) of same name as of calling Model's Property
*#
#{
var modelMetadata = ViewData.ModelMetadata;
// Get property name of the model
var propertyname = modelMetadata.PropertyName;
}
#if (ViewData[propertyname] == null)
{
#Html.DropDownList(propertyname , Enumerable.Empty<SelectListItem>(), "--Select--", new { #class = "form-control" })
}
else
{
#Html.DropDownList(propertyname , null, "--Select--", new { #class = "form-control" })
}
now using it as
#Html.EditorFor(i=>i.Country,"CustomDropDown")
I also have a ViewBag.Country as SelectList of countries.
Everything works fine, but now the Naming of the Control becomes
<select class="form-control" id="Country_Country" name="Country.Country">
how to remove the additional Country from the id and name?
Additional Info:
I could have just used the #Html.DropDownList("Country") but it doesn't allow me to add the css class to the control.
I think i found the Solution.
I changed the DropDownList to DropDownListFor with some changes
#if (ViewData[propertyname] == null)
{
#Html.DropDownListFor(m=>m, Enumerable.Empty<SelectListItem>(), "--Select--", new { #class = "form-control" })
}
else
{
#Html.DropDownListFor(m => m, ViewData[propertyname] as SelectList, "--Select--", new { #class = "form-control" })
}
this auto ViewData bind is kind of confusing at times. >_<

How do I add placeholder text from the model into a MVC view?

I have a model:
[DataType(DataType.EmailAddress)]
[DisplayFormat(ConvertEmptyStringToNull = true)]
[Display(Prompt = "Email Address")]
public string Email { get; set; }
I am trying to get the "prompt" to show in the placeholder text of the resulting text box with the following:
#Html.EditorFor(model => model.Email,
new { htmlAttributes = new { #class = "form-control input-md",
placeholder = #ViewData.ModelMetadata.Watermark } })
When I view the generated HTML I only get "placeholder" in the input tag. According to what I have read ViewData.ModelMetadata.Watermark should work. What is the correct way to get this placeholder text in place?
This solved my issue:
#Html.EditorFor(model => model.Email, new { htmlAttributes =
new { #class = "form-control input-sm",
placeholder = #Html.DisplayNameFor(m=>m.Email) } })
The code that did it was
placeholder = #Html.DisplayNameFor(m=>m.Email)
A little late, but if someone is still looking for it...
#Html.EditorFor(model => model.Email,
new { htmlAttributes = new { #class = "form-control input-md",
#placeholder = "Whatever you want as a placeholder" } })
It's perfect and clean!
The correct solution to get the Prompt value instead of the DisplayName in a non-templated control context is the following:
#Html.EditorFor(model => model.Email,
new { #class = "form-control input-md",
placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark
})
This will also - unlike the accepted solution using #Html.DisplayNameFor(m=>m.Email) - not double-escape the watermark text, which depending on the text and the language displayed can be a problem.
Use TextBoxFor:
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.Email) })
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" , #placeholder = "Username" })
I know, i'm a bit late, but an extension method ad-hoc like this one is the best solution imho:
public static string UnencodedDisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var displayName = html.DisplayNameFor(expression).ToString();
var unencodedDisplayName = HttpUtility.HtmlDecode(displayName);
return unencodedDisplayName;
}
Usage:
#Html.EditorFor(model => model.Email, new
{
htmlAttributes = new
{
#class = "form-control input-sm",
placeholder = Html.UnencodedDisplayNameFor(m => m.Email)
}
})
This solution won't add complexity (like using ModelMetadata) or duplicate labels (like some other answers), and provides full support on accents.
Use TextBoxFor like so:
#Html.TextBoxFor(model => model.LastName, new{placeholder="Last Name"})
In your controller method that renders view say
ViewData["Name"] = "blabbity blah";
then
#Html.TextBoxFor(u => u.Company, new { #placeholder = #ViewData["Name"] })
Actually better yet you can do this.
public ActionResult Index()
{
NewLogin n = new ClassModel().PopModel();
n.Company = "fsdfsdf";
return View(n);
}
#Html.TextBoxFor(u => u.Company, new { #placeholder = Model.Company })
Check out this answers to this question, which has been answered aleady (a few times).
Html attributes for EditorFor() in ASP.NET MVC
ASP.NET MVC 3 Razor - Adding class to EditorFor
#Html.EditorFor uses templates, and so the approach to this problem is using a customised template.
you can use it as follows for the date which will also give you a "datetime" picker.
[DisplayFormat(DataFormatString ="{0:yyyy-MM-dd}",ApplyFormatInEditMode =true)]

Using a html select box with razor

I have a html selector, and I want to use the selected value for my "model => model.type" in my form. Is there a way to set the value in my #Html.EditorFor(model => model.type) to the value of the selector?
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Bet</legend>
<div class="editor-label">
#Html.LabelFor(model => model.type)
</div>
<div class="editor-field">
<select id ="type">
<option value="Football">Football</option>
<option value="Rugby">Rugby</option>
<option value="Horse Racing">Horse Racing</option>
</select>
#Html.EditorFor(model => model.type)
#Html.ValidationMessageFor(model => model.type)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
You can try with this options:
Model:
public string Type { get; set; }
public IEnumerable<SelectListItem> TypeList
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "Football", Value = "Football"},
new SelectListItem { Text = "Rugby", Value = "Rugby"},
new SelectListItem { Text = "Horse Racing", Value = "Horse Racing"}
};
}
}
HTML (Razor):
#Html.DropDownListFor(model => model.Type, Model.TypeList)
OR
HTML (Razor):
#Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, Model.Type))
#andresdescalzo's solution (last one) works with a minor change:
#Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, "Rugby"), htmlAttributes: new { #class = "form-control" })
First: Add a selected item for dropdown list (e.g. "Rugby")
Second: remove last Model.Type and add htmlAttributes
PS: SelectedList open parentheses closed after selected item of list (here is "Rugby")
The solution provided by #andresdescalzo works only when we pass the model from Controller to the view.
public class SomeController : Controller
{
public ActionResult SomeAction()
{
return View(new SomeModelWithIEnumerationsSelectListItem())
}
}
An addition to the existing answers: If you get the exception "object reference not set to an instance of an object" when implementing #andresdescalzo's solution, you either need to:
Return the model that you are working with as #diwas mentioned
Instantiate a model on the razor page so you can call the method. This is helpful if you are using a ViewModel instead of a simple EF model.
The second can be done like this:
#{ var tempModel = new YourNameSpace.Models.YourModel(); }
#Html.DropDownListFor(model => model.Type, tempModel.TypeList, Model.Type))
This is the Razor View
<div class="editor-field col-md-3">
#Html.DropDownListFor(model => model.Servers,
Model.AvailableServers,new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SqlServerName)
</div>
Dynamic DropDown from controller
List<SelectListItem> ServersAvailable = new List<SelectListItem>();
bool IdSelected = false;
ServersAvailable.Add(new SelectListItem { Text = "......Select your server name......", Value = "" });
for (int i = 0; i < dt.Rows.Count; i++)
{
ServersAvailable.Add(new SelectListItem
{
Text = dt.Rows[i].ItemArray[0].ToString(),
Value = dt.Rows[i].ItemArray[0].ToString(),
Selected = IdSelected
});
}

MVC4 SelectList not selected default object

My select list isn't selecting the default object being brought in through code.
I first create my SelectList like so:
public SelectList CreateSelectList(object objSelected = null)
{
return new SelectList(GetAll().OrderBy(s => s.NumericalValue), "PeriodID", "Name", objSelected);
}
My objSelected gets filled with a Guid that's associated with the PeriodID.
Inside my controller I define my viewbag variable to the new select list.
public ActionResult Edit(Guid id)
{
Classroom classroom = classroomRepository.GetByID(id);
ViewBag.PeriodID = periodRepository.CreateSelectList(classroom.PeriodID);
return View(classroom);
}
Then in my View here's how I'm displaying my SelectList:
<div class="control-group">
#Html.LabelFor(model => model.PeriodID, "Period", new { #class = "control-label" })
<div class="controls">
#Html.DropDownListFor(model => model.PeriodID, ViewBag.PeriodID as SelectList, String.Empty, new { #class = "span3" })
#Html.ValidationMessageFor(model => model.PeriodID)
</div>
</div>
You have two problems here. First, this:
#Html.DropDownListFor(model => model.PeriodID, ViewBag.PeriodID as SelectList,
String.Empty, new { #class = "span3" })
Change ViewBag.PeriodID to ViewBag.Periods or ViewBag.PeriodList. This is confusing, and there are a number of situations in which MVC will get confused if you use the same named object. It's just best to make sure everything is named differently.
Second, The SelectList class ignores the selecteditem member of the SelectListItem. It's not used at all. DropDownListFor will take the value of model.PeriodID and make it the selected value. However, I see in your code that those should be the same so I'm guessing the naming may be a factor here.

Resources