Problem with form Ubmit

Asked

Viewed 166 times

0

I’m having trouble trying to make a form Ubmit when my object is null as it is not required. However it is not possible to save with it null.

/// Model
public class Atividade {
    public virtual long Id { get; set; }

    [Display(Name = "Descrição")]
    [Required(ErrorMessage = "É necessário informar uma descrição.")]
    public virtual string Descricao { get; set; }

    [Display(Name = "Cliente")]
    public virtual Cliente Cliente{ get; set; }
}

public class Cliente : BaseEntity
{
    [Display(Name = "Razão Social")]
    [Required(ErrorMessage = "É necessário informar a Razão Social.")]
    [StringLength(100, ErrorMessage = "Existe um limite de 100 caracteres.")]
    public virtual string RazaoSocial { get; set; }

    [Display(Name = "Nome Fantasia*")]
    [Required(ErrorMessage = "É necessário informar o Nome Fantasia.")]
    [StringLength(150, ErrorMessage = "Existe um limite de 150 caracteres.")]
    public virtual string NomeFantasia { get; set; }

    [Display(Name = "Tipo*")]
    [Required(ErrorMessage = "É necessário informar Tipo de Pessoa.")]
    public virtual ETipoPessoa ETipoPessoa { get; set; }

    [Display(Name = "CPF/CNPJ")]
    public virtual string CpfCnpj { get; set; }

    [Display(Name = "Situação")]
    public virtual Cliente_Situacao Cliente_Situacao { get; set; }

    [Display(Name = "Classe")]
    public virtual Cliente_Classe Cliente_Classe { get; set; }

    public virtual Cliente ResponsavelLegal { get; set; }


    public Cliente()
    {
        DataCadastro = DataCadastro == new DateTime() ? DateTime.Now : DataCadastro;
    }
}

/// Mapping
public AtividadeMap : ClassMap<Atividade>{
    public AtividadeMap(){
         Id(x => x.Id);

         Map(x => x.Descricao);
         References(x => x.Cliente).Nullable;

         Table("Atividade");
    }
}

/// Controller
public void Salvar(Atividade modelo){...}

/// View
@using (Html.BeginForm("Salvar", "Atividade", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    @Html.HiddenFor(model => model.Id)

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.TextBoxFor(model => model.Descricao, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Cliente, htmlAttributes: new { @class = "control-label" })
        @Html.DropDownListFor(model => model.Cliente.Id, new List<SelectListItem>(), "Nenhum", new { @class = "form-control", onchange = "getOportunidade(this);" })
        <small>@Html.ValidationMessageFor(model => model.Cliente, "", new { @class = "text-danger" })</small>
    </div>

    <div class="form-actions" align="right">
        <button type="submit" class="btn-success " > <i class="fa fa-check"></i> Salvar</button>
    </div>
}

Then I realize that the HTML generated by Razor was like this:

 <select class="form-control input-validation-error" data-val="true" 
data-val-number="O campo Id deve ser um número." data-val-required="O campo Id é obrigatório." 
id="Cliente_Id" name="Cliente.Id" onchange="getOportunidade(this);"
aria-describedby="Cliente_Id-error" aria-invalid="true">
<option value="null">Nenhum</option>
<option value="31">Édipo A.</option>
<option value="6">João J.</option>
<option value="30">Rodrigo S.</option></select>

By pressing the save button, my Dropdownlistfor() is focused. Only when selected a Client is the template sent to the server... Does anyone know what I must do so that this field can be saved with null value?

  • has already been in the database and set null in the field there in the database? which field should be null? What error message?

  • It does not arrive on the server, hence it is not saved in the database. The field that should be null is the 'Client' field. No error message, only the client field is focused, type obliging to enter a value to be able to save.

1 answer

1


You need to inform that the field is not mandatory, change your class to

public class Atividade {
    public long? Id { get; set; }
    public Cliente Cliente{ get; set; }
}

the ? allows the field to be nullable

  • Yes, but the problem is happening in the Client but I could not create: public Client? Client { get; set; }

  • No, Client is an object and they accept null. What must be happening is that your database is not accepting the client to be null. are you using Entity? if yes, are you making any model configuration in the bank? pq when adding the ? was to have created a migration that would allow the null registration of Client.

  • I’m using Nhibernate, updated the question with my mapping so you can take a look...

  • But it looks like some kind of javascript validation done by @Html.Dropdownlistfor()

  • The error is only at the front? vc is doing some validation in the field with data annotation? remove the @Html.ValidationMessageFor client

  • Yes! It happens at the front. Oh and I am using yes, I forgot to mention, but in the client field the only data Annotation I am using is [Display("Client")]

  • Please add your class Cliente in the question

  • Update her with my client class

  • where the countryside is id customer’s?

  • It is inside the Baseentity, which only contains the property: public virtual long Id {get; set;}

  • 1

    So that’s why the field is being required, this field public virtual long Id {get; set;} does not allow nullable

  • I just did one more test where I created the dropdownlist HTML without using 'Html Helper', I simply declared a <select> and valued it. So Submit! worked The problem is apparently when using 'Html.Helper Razor'. This will be the only solution?

  • 1

    Actually the problem isn’t using the Html.Helper Razor because it "understands" what is being requested by the model, from the moment that the id field does not accept nullable it will create validation. Try using helper, but remove the @Html.ValidationMessageFor, removing this helper is to lose validation front-end

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.