Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor: @Html.HiddenFor() need to turn off validation

Could you help me, please.

I have a class:

public class Product
{
   ...

   // NOT REQUIRED!
   public virtual Category Category{ get; set; }
}

But when in a view I create

@Html.HiddenFor(model => model.Category.Id), or
@Html.Hidden("model.Category.Id", model => model.Category.Id)

razor adds validation attribute to this.

  1. How to turn it off? (in model, in view)
  2. How to turn off validation event if a property has the attribute [Required]?

I found out that this is not a razor problem, it is somewhere in MVC. Even if I manage to pass "Category.Id" value = "" to the server, TryModelUpdate() will fail - it requires "Category.Id" to be set, but it's not required in my model.

Why is it so??!

like image 949
drawer Avatar asked Nov 14 '22 19:11

drawer


1 Answers

I solved the same issue with an crutch like this:

  @{ Html.EnableUnobtrusiveJavaScript(false); }

  @Html.HiddenFor(t => t.Prop1)
  @Html.HiddenFor(t => t.Prop2)

  ...

  @{ Html.EnableUnobtrusiveJavaScript(true); }

like image 106
Maxim Savencov Avatar answered Dec 26 '22 02:12

Maxim Savencov