Dropdownlist in views Asp.net mvc of the validation error

Asked

Viewed 221 times

0

In a view razor of asp.net mvc I have a dropdownlist with the following code:

@Html.DropDownListFor(model => model.Banco, (SelectList) ViewBag.Banco, new {@class = "form-control"})

Even selecting the value, when validated in the controller, as ModelState.IsValid, error always says that the selected value is invalid, but actually it is not, the Id selected is correct. You can ignore the validation of this field or fix it?

  • Where are you checking this Modelstate.Isvalid?

  • in the controller, in the action that persists the information in the database.

  • Please post exactly what your Modelstate is returning as a validation error.

  • You are returning this message: "The value '1' is invalid." 1 is the Id of the selected database.

  • 1

    It has to put the code of the controller also?

  • 1

    Take advantage and put the Model code too

Show 1 more comment

2 answers

1

You can do in the scope of an Action that receives the template of your submitted fomulário

[HttpPost]
public ActionResult Edit([Bind(Exclude="Banco")]CompanyDto model)
{
    // ...
}

You can also describe the property in the scope of your model since when this way will be influenced throughout the application and not only in the Action being used.

[Bind(Exclude="Propriedade_1,Propriedade_2,Propriedade_3")]
public class CompanyDto
{
  public int Id { get; set; }
  public string Propriedade_1 { get; set; }
  public string Propriedade_2 { get; set; }
  public string Propriedade_3 { get; set; }
  // ...
}

You can also filter a property of an example model object

public class CompanyDto
{
  public int Id { get; set; }
  [Exclude]
  public string Propriedade_1 { get; set; }
  public string Propriedade_2 { get; set; }
  public string Propriedade_3 { get; set; }
  // ...
}

Another way to check is to put a breakpoint in the Action that receives the data and before that in the browser price F12 and check the value of the item that has the 'Selected' property of your dropdown before you submit the form, for Action.

  • I found your answer very good Rodrigo, very interesting, but I managed to do what I wanted, thank you.

0


I managed to solve the problem, I was doing wrong, I changed to point to the Bank ID and not to the bank itself and it worked:

@HTML.Dropdownlistfor(model => model.Banco.Id, (Selectlist) Viewbag.Bank, new {@class = "form-control"})

Browser other questions tagged

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