AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

ASP.NET MVC dropdownlist value field xxx must be a number?

model

public partial class TblMusteriler { 
    public TblMusteriler() { 
       this.TblSayaclar = new HashSet<TblSayaclar>(); 
    } 
    public System.Guid sno { get; set; } 

    [Display(Name = "Müşteri No")] 
    [Required(ErrorMessage = "Müşteri numarası boş geçilemez.")] 
    public string musteri_no { get; set; } 

    [Display(Name = "Müşteri Adı")] 
    [Required(ErrorMessage = "Müşteri adı boş geçilemez.")] 
    public string musteri_adi { get; set; }

controller

public ActionResult SayacEkle()
{
    var musteriler = entity.TblMusteriler.Select(x => new { x.sno, x.musteri_adi });
    ViewBag.musteri_id = new SelectList(musteriler.AsEnumerable(), "sno", "musteri_adi");

    return ContextDependentView(new TblSayaclar());
}

View

@Html.DropDownList("sno", (SelectList)ViewBag.musteri_id, "--Müşteri Seçiniz--")

HTML output

<select data-val="true" data-val-number="The field sno must be a number." data-val-required="The sno field is required." id="sno" name="sno" class="input-validation-error"><option value="">--Müşteri Seçiniz--</option>

I should not change sno type to number. It must be guid type. How can I use guid type as a value in dropdownlist?

Thanks.

Upvotes: 0

Views: 1017

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039100

If you want to override the error message you could use a nullable Guid and the Required attribute:

[Required(ErrorMessage = "Please select a valid SNO")]
public System.Guid? sno { get; set; }

And if you want the default metadata provider to implicitly add the Required attribute for nullable types you could set the AddImplicitRequiredAttributeForValueTypes property in your Application_Start to false:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Upvotes: 1

Related Questions