MVC4 not displaying DefaultValues - view

In my model:
[Required]
[DefaultValue("Some text ...")]
public string SomeValue{ get; set; }
In my view:
#Html.TextBoxFor(model => model.SomeValue)
At start the textbox is empty, I'd like it to contain the default value.
Thank you if you can help me.

You need to set the value in the constructor of your model...
public class MyModel {
public MyModel() {
SomeValue = "Some text...";
}
[Required]
[DefaultValue("Some text ...")]
public string SomeValue{ get; set; }
}
The DefaultValueAttribute isn't for setting the value - it is for comparing it later. For example, when the model is mapped from the user input, you can check if SomeValue has been entered or not because you can check whether it is the same as DefaultValue.

http://support.microsoft.com/kb/311339
[...] However, the DefaultValue attribute does not cause the initial value to be initialized with the attribute's value.

Related

Model validation attribute [Required] doesn't accept a string of all spaces

I'm working with ASP.Net MVC 4 website project.
When I set the attribute Required for a model property.
[Display(Name = "Some Model Property:")]
[Required]
public string SomeModelProperty{ get; set; }
This will mark the input field to be red when its value is empty.
My issue is that this field is also marked red when its value is all spaces
I want to allow input value to have all spaces only for a Required property.
How can I get to that?
You should use:
[Required(AllowEmptyStrings = true)]
And if the length of the string matters add:
[MinLength(1)]
You could create your own ValidationAttribute to do the job.
public class MostlyRequiredAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
return value != null && !string.IsNullOrEmpty(value.ToString());
}
}
[Display(Name = "Venue Assigned Abstract Tracking Number:")]
[MostlyRequired]
public string SomeModelProperty{ get; set; }

Required attribute not displaying

Public Class Duration
{
[Required]
Public DurationUnit Unit
[Required]
Public int Length
}
Public Class Employee
{
[RequiredAttribute]
public virtual Duration NotificationLeadTime { get; set; }
}
The fields Unit and Length, when not suplied are getting highlighted in Red but the error message is not getting displayed.
I tries also giving [Required(ErrorMessage="sadfdsf")],but this is also not working.
I also tried inheriting the class with IValidatableObject but that also didn't work.
How to display the error message ?
You should use properties, not fields:
public class Duration
{
[Required]
public DurationUnit Unit { get; set; }
[Required]
public int Length { get; set; }
}
In order to display the corresponding error message use the Html.ValidationMessageFor helper.
For example:
#Html.EditorFor(x => x.NotificationLeadTime.Unit)
#Html.ValidationMessageFor(x => x.NotificationLeadTime.Unit)
By the way it doesn't really make sense to decorate a non-nullable type such as int with the [Required] attribute because those types always have a default value. You should make it a nullable integer instead. Same remark stands for the DurationUnit property if DurationUnit is an enum.

Problems converting an entity property to HiddenField in MVC

I have a Supplier Entitiy that contains
ID - int
Status - string
Name - string
CreateDate- datetime
I am using the partial class method to create Data Annotations for the above Entity.as described here
[MetadataType(typeof(SupplierMetadata))]
public partial class Supplier
{
// Note this class has nothing in it. It's just here to add the class-level attribute.
}
public class SupplierMetadata
{
// Name the field the same as EF named the property - "FirstName" for example.
// Also, the type needs to match. Basically just redeclare it.
// Note that this is a field. I think it can be a property too, but fields definitely should work.
[HiddenInput]
public Int32 ID;
[Required]
[UIHint("StatusList")]
[Display(Name = "Status")]
public string Status;
[Required]
[Display(Name = "Supplier Name")]
public string Name;
}
the HiddenInput annotation throws an error saying "Attribute 'HiddenInput' is not valid on this declaration type. It is only valid on 'class, property, indexer' declarations."
Please help
The error states that that attribute can only be added to 'class, property, or indexer declarations'.
public Int32 ID; is none of these - it is a field.
If you change it to a property
public Int32 ID { get; set; } you will be able to decorate it with that attribute.
All of your properties are defined incorrectly as they are missing the get/set accessors. All properties in .NET require getter and/or setter accessors. Change your code to this:
public class SupplierMetadata
{
[HiddenInput]
public Int32 ID { get; set; }
[Required]
[UIHint("StatusList")]
[Display(Name = "Status")]
public string Status { get; set; }
[Required]
[Display(Name = "Supplier Name")]
public string Name { get; set; }
}

asp.net mvc 3 razor get one element from IEnumerable

I my view model(LIST) looks like this:
public class ConversationModel
{
public int ID { get; set; }
public string Body { get; set; }
public DateTime Datetime { get; set; }
public string Username { get; set; }
public string ImgUrl { get; set; }
public string ToUserID{ get; set; }
}
this is my view
#model IEnumerable<NGGmvc.Models.ConversationModel>
how i can get ToUserID on current postion? something like this
#Model[0].ToUserID
Thanks
You should be able to do:
#Model.First().ToUserID
Note, you may want to check whether there are any items in the enumerable first as if there aren't, then First() will return null
(Note, because you had #Model[0] in your question, I assume you are specifically trying to get the first value. I may have the wrong end of the stick, in which case Jakub's answer should sort you out!)
You should be able to use the following:
#Model.First().ToUserID
However, if your model will only ever reference the first element of the enumeration in the view, I would recommend that you only pass that element to the view.
For example:
#model ConversationModel
#Model.ToUserID
And in the controller only pass the first element that is required:
List<ConversationModel> conversationList = //your conversation model initialisation code
return View(conversationList.First());
#foreach(var model in Model)
{
#model.ToUserID
}

MVC3 Optional parameters

This is a follow up to this:
What does MVC3 do with C# Optional Parameters?
I have an action with the following signature:
public ViewResult Show(int Id, PublishingErrorSummary pubErrors=null, String title=null)
On requesting server/show/1 pubErrors is not null, but title is null. How is it possible? These are just two objects but string somehow manages to become null. Where can I fix this?
Edit: class definition added
public class PublishingErrorSummary
{
public List<string> StepOneErrors { get; set; }
public List<string> StepTwoErrors { get; set; }
public List<string> StepThreeErrors { get; set; }
public List<string> StepFourErrors { get; set; }
}
PublishingErrorSummary is a complex object. The default model binder always initializes complex objects. It doesn't really make sense to set its default value to null. Same stands for the title parameter. Strings are reference types and their default value will be null anyway if no request parameter title is sent.

Resources