Trying to formate the DateTime to Date in ViewModel but it does'nt work.
ViewModel
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? TargetCompletionDate { get; set; }
View
#Html.TextBoxFor(m => m.TargetCompletionDate, new { style = "width: 100px;" })
(Solved)I made it as #Html.EditorFor and works fine.
Thanks.
#Html.EditorFor(m => m.TargetCompletionDate, new { style = "width: 100px;" })
Related
I have populated a DropDownListFor with all the correct values. I'm passing a Guid parameter, but don't know how to set the default value to that Guid.
View
<div class="form-group">
#Html.LabelFor(model => model.Parent)
#Html.DropDownListFor(model => model.Parent, new SelectList(Model.AllParents, "Id", "Name"), string.Empty, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Parent)
</div>
ViewModel
public class ParentViewModel
{
public List<Parent> AllParents { get; set; }
[DisplayName("Parent")]
public Guid? ParentId { get; set; }
}
Controller
[HttpGet]
public ActionResult Create(Guid? id)
{
var parentViewModel = new ParentViewModel
{
AllParents = _Service.GetAll().ToList()
};
return View(parentViewModel);
}
}
You need to replace string.Empty with "Default value do you want"
#Html.DropDownListFor(model => model.Parent, new SelectList(Model.AllParents, "Id", "Name"), "Default value is here here", new { #class = "form-control" })
Client side validation is not working...
same process I have done in another page its working but there have not used forloop.
Here when I type the text without doing the validation simply tick image is displaying... give me solution..
View is
#model IList<clientval.Models.ShoppingClass>
#using (Html.BeginForm("Login", "Home"))
{
for (int i =0; i <1; i++)
{
<table>
<tr>
<td>#Html.Label("FirstName")</td>
<td>#Html.TextBox("FirstName")<div>#Html.ValidationMessageFor(o => o[i].FirstName)</div></td>
<td>#Html.Label("LastName")</td>
<td>#Html.TextBox("LastName")<div>#Html.ValidationMessageFor(o => o[i].LastName)</div></td>
<tr>
}
}
Script is
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="../../assets/js/ClientScript.js" type="text/javascript"></script>
Controller is
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Guestlogin(string firstname, string lastname)
{
ShoppingClass s = new ShoppingClass();
var button = Request["button"];
var ob = s.Newcustomer(customerfirstname, customerlastname);
TempData["BN"] = ob;
return RedirectToAction("Sucessfully", ob);
}
Model is
[Required(ErrorMessage = "First Name is Required")]
[RegularExpression(#"^[a-zA-Z ]*$", ErrorMessage = "First Name is Not valid")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is Required")]
[RegularExpression(#"^[a-zA-Z ]*$", ErrorMessage = "Last Name is Not valid")]
public string LastName { get; set; }
public List<ShoppingClass> Newcustomer(string firstname, string lastname)
{
List<ShoppingClass> list = new List<ShoppingClass>();
ShoppingClass obj = new ShoppingClass();
.
.
.
}
Not really sure what you're doing with the for-loop, but I'm guessing that's just an example?
Shouldn't you be using TextBoxFor and LabelFor like this:
#using (Html.BeginForm("Login", "Home"))
{
for (int i =0; i <1; i++)
{
<table>
<tr>
<td>#Html.LabelFor(o => o[i].FirstName)</td>
<td>#Html.TextBoxFor(o => o[i].FirstName)<div>#Html.ValidationMessageFor(o => o[i].FirstName)</div></td>
<td>#Html.LabelFor(o => o[i].LastName)</td>
<td>#Html.TextBoxFor(o => o[i].LastName)<div>#Html.ValidationMessageFor(o => o[i].LastName)</div></td>
<tr>
}
}
Try this:
Html.Validate("FirstName");
Like this on all fields
I want to make readOnly with EditorFor in edit page.
I tried to put readonly and disabled as:
<div class="editor-field">
#Html.EditorFor(model => model.userName, new { disabled = "disabled", #readonly = "readonly" })
</div>
However, it does not work. How can I make to disable edit this field?
Thank you.
The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:
<div class="editor-field">
#Html.TextBoxFor(model => model.userName, new
{ disabled = "disabled", #readonly = "readonly" })
</div>
You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:
public class MyModel
{
[UIHint("userName")]
public string userName { ;get; set; }
}
Then, in your Views/Shared/EditorTemplates folder, create a file userName.cshtml. In that file, put this:
#model string
#Html.TextBoxFor(m => m, new { disabled = "disabled", #readonly = "readonly" })
This code is supported in MVC4 onwards
#Html.EditorFor(model => model.userName, new { htmlAttributes = new { #class = "form-control", disabled = "disabled", #readonly = "readonly" } })
For those who wonder why you want to use an EditoFor if you don`t want it to be editable, I have an example.
I have this in my Model.
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0: dd/MM/yyyy}")]
public DateTime issueDate { get; set; }
and when you want to display that format, the only way it works is with an EditorFor, but I have a jquery datepicker for that "input" so it has to be readonly to avoid the users of writting down wrong dates.
To make it work the way I want I put this in the View...
#Html.EditorFor(m => m.issueDate, new{ #class="inp", #style="width:200px", #MaxLength = "200"})
and this in my ready function...
$('#issueDate').prop('readOnly', true);
I hope this would be helpful for someone out there.
Sorry for my English
You can do it this way:
#Html.EditorFor(m => m.userName, new { htmlAttributes = new { disabled = true } })
I know the question states MVC 3, but it was 2012, so just in case:
As of MVC 5.1 you can now pass HTML attributes to EditorFor like so:
#Html.EditorFor(x => x.Name, new { htmlAttributes = new { #readonly = "", disabled = "" } })
Try using:
#Html.DisplayFor(model => model.userName) <br/>
#Html.HiddenFor(model => model.userName)
Here's how I do it:
Model:
[ReadOnly(true)]
public string Email { get { return DbUser.Email; } }
View:
#Html.TheEditorFor(x => x.Email)
Extension:
namespace System.Web.Mvc
{
public static class CustomExtensions
{
public static MvcHtmlString TheEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
{
return iEREditorForInternal(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
private static MvcHtmlString iEREditorForInternal<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
if (htmlAttributes == null) htmlAttributes = new Dictionary<string, object>();
TagBuilder builder = new TagBuilder("div");
builder.MergeAttributes(htmlAttributes);
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string labelHtml = labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();
if (metadata.IsRequired)
labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression, new { #class = "required" }).ToHtmlString();
string editorHtml = Html.EditorExtensions.EditorFor(htmlHelper, expression).ToHtmlString();
if (metadata.IsReadOnly)
editorHtml = Html.DisplayExtensions.DisplayFor(htmlHelper, expression).ToHtmlString();
string validationHtml = Html.ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString();
builder.InnerHtml = labelHtml + editorHtml + validationHtml;
return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
}
}
}
Of course my editor is doing a bunch more stuff, like adding a label, adding a required class to that label as necessary, adding a DisplayFor if the property is ReadOnly EditorFor if its not, adding a ValidateMessageFor and finally wrapping all of that in a Div that can have Html Attributes assigned to it... my Views are super clean.
Create an EditorTemplate for a specific set of Views (bound by one Controller):
In this example I have a template for a Date, but you can change it to whatever you want.
Here is the code in the Data.cshtml:
#model Nullable<DateTime>
#Html.TextBox("", #Model != null ? String.Format("{0:d}", ((System.DateTime)Model).ToShortDateString()) : "", new { #class = "datefield", type = "date", disabled = "disabled" #readonly = "readonly" })
and in the model:
[DataType(DataType.Date)]
public DateTime? BlahDate { get; set; }
Old post I know.. but now you can do this to keep alignment and all looking consistent..
#Html.EditorFor(model => model.myField, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
I use the readonly attribute instead of disabled attribute - as this will still submit the value when the field is readonly.
Note: Any presence of the readonly attribute will make the field readonly even if set to false, so hence why I branch the editor for code like below.
#if (disabled)
{
#Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { #class = "form-control", #readonly = "" } })
}
else
{
#Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { #class = "form-control" } })
}
<div class="editor-field">
#Html.EditorFor(model => model.userName)
</div>
Use jquery to disable
<script type="text/javascript">
$(document).ready(function () {
$('#userName').attr('disabled', true);
});
</script>
i think this is simple than other by using [Editable(false)] attribute
for example:
public class MyModel
{
[Editable(false)]
public string userName { get; set; }
}
I am new to MVC3
I am finding it difficult to create an dropdown.I have gone through all the other related questions but they all seem to be complex
I jus need to create a dropdown and insert the selected value in database
Here is what i have tried:
//Model class:
public int Id { get; set; }
public SelectList hobbiename { get; set; }
public string filelocation { get; set; }
public string hobbydetail { get; set; }
//Inside Controller
public ActionResult Create()
{
var values = new[]
{
new { Value = "1", Text = "Dancing" },
new { Value = "2", Text = "Painting" },
new { Value = "3", Text = "Singing" },
};
var model = new Hobbies
{
hobbiename = new SelectList(values, "Value", "Text")
};
return View();
}
//Inside view
<div class="editor-label">
#Html.LabelFor(model => model.hobbiename)
</div>
<div class="editor-field">
#Html.DropDownListFor( x => x.hobbiename, Model.hobbiename )
#Html.ValidationMessageFor(model => model.hobbiename)
</div>
I get an error:System.MissingMethodException: No parameterless constructor defined for this object
You are not passing any model to the view in your action. Also you should not use the same property as first and second argument of the DropDownListFor helper. The first argument that you pass as lambda expression corresponds to a scalar property on your view model that will hold the selected value and which will allow you to retrieve this value back when the form is submitted. The second argument is the collection.
So you could adapt a little bit your code:
Model:
public class Hobbies
{
[Required]
public string SelectedHobbyId { get; set; }
public IEnumerable<SelectListItem> AvailableHobbies { get; set; }
... some other properties that are irrelevant to the question
}
Controller:
public class HomeController: Controller
{
public ActionResult Create()
{
// obviously those values might come from a database or something
var values = new[]
{
new { Value = "1", Text = "Dancing" },
new { Value = "2", Text = "Painting" },
new { Value = "3", Text = "Singing" },
};
var model = new Hobbies
{
AvailableHobbies = values.Select(x => new SelectListItem
{
Value = x.Value,
Text = x.Text
});
};
return View(model);
}
[HttpPost]
public ActionResult Create(Hobbies hobbies)
{
// hobbies.SelectedHobbyId will contain the id of the element
// that was selected in the dropdown
...
}
}
View:
#model Hobbies
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.SelectedHobbyId)
#Html.DropDownListFor(x => x.SelectedHobbyId, Model.AvailableHobbies)
#Html.ValidationMessageFor(x => x.SelectedHobbyId)
<button type="submit">Create</button>
}
I would create them as
Model:
public class ViewModel
{
public int Id { get; set; }
public string HobbyName { get; set; }
public IEnumerable<SelectListItem> Hobbies {get;set; }
public string FileLocation { get; set; }
public string HobbyDetail { get; set; }
}
Action
public ActionResult Create()
{
var someDbObjects= new[]
{
new { Id = "1", Text = "Dancing" },
new { Id = "2", Text = "Painting" },
new { Id = "3", Text = "Singing" },
};
var model = new ViewModel
{
Hobbies = someDbObjects.Select(k => new SelectListItem{ Text = k, Value = k.Id })
};
return View(model);
}
View
<div class="editor-label">
#Html.LabelFor(model => model.HobbyName)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.HobbyName, Model.Hobbies )
#Html.ValidationMessageFor(model => model.HobbyName)
</div>
I want to have a dropdownlist in my view that displays a patient's ID, First Name, and Last Name. With the code below, it displays each patient's First Name. How can I pass all three properties into the viewbag and have them display in the dropdownlist?
Controller
public ActionResult Create()
{ViewBag.Patient_ID = new SelectList(db.Patients, "Patient_ID", "First_Name");
return View();
}
View
<div class="editor-field">
#Html.DropDownList("Patient_ID", String.Empty)
#Html.ValidationMessageFor(model => model.Patient_ID)
</div>
Thanks.
Ok, I have edited my code as follows, and I receive the error "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedPatientId'."
Controller
public ActionResult Create()
{
var model = new MyViewModel();
{
var Patients = db.Patients.ToList().Select(p => new SelectListItem
{
Value = p.Patient_ID.ToString(),
Text = string.Format("{0}-{1}-{2}", p.Patient_ID, p.First_Name, p.Last_Name)
});
var Prescribers = db.Prescribers.ToList().Select(p => new SelectListItem
{
Value = p.DEA_Number.ToString(),
Text = string.Format("{0}-{1}-{2}", p.DEA_Number, p.First_Name, p.Last_Name)
});
var Drugs = db.Drugs.ToList().Select(p => new SelectListItem
{
Value = p.NDC.ToString(),
Text = string.Format("{0}-{1}-{2}", p.NDC, p.Name, p.Price)
});
};
return View(model);
}
View Model
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
[Required]
public int? SelectedPrescriber { get; set; }
public IEnumerable<SelectListItem> Prescribers { get; set; }
[Required]
public int? SelectedDrug { get; set; }
public IEnumerable<SelectListItem> Drugs { get; set; }
}
View
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
#Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
#Html.DropDownListFor(
x => x.SelectedPrescriber,
Model.Patients,
"-- Select prescriber ---"
)
#Html.ValidationMessageFor(x => x.SelectedPrescriber)
<button type="submit">OK</button>
}
I would recommend you not to use any ViewBag at all and define a view model:
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
}
and then have your controller action fill and pass this view model to the view:
public ActionResult Create()
{
var model = new MyViewModel
{
Patients = db.Patients.ToList().Select(p => new SelectListItem
{
Value = p.Patient_ID.ToString(),
Text = string.Format("{0}-{1}-{2}", p.Patient_ID, p.First_Name, p.Last_Name)
});
};
return View(model);
}
and finally in your strongly typed view display the dropdown list:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
#Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
}
Easy way to accomplish that is just creating additional property on your model either by modifying model class or adding/modifying a partial class
[NotMapped]
public string DisplayFormat
{
get
{
return string.Format("{0}-{1}-{2}", Patient_ID, First_Name, Last_Name);
}
}