Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React with MVC data annotations and unobtrusive validation

We are currently looking to experiment with modern frontend frameworks like react on an MVC4 project. We use data annotations in our models and we have a lot of forms that use unobtrusive validation on the UI.

The main thing is finding a way to use react to generate the content while still being able to make use of features like unobtrusive validation. As I understand it, it really is just a bunch of data-val attributes dynamically generated when using HTML helpers like TextAreaFor, ValidationMessageFor with the attributes getting values from the data annotations in the model classes.

I've tried several things including

 ReactDOM.render(
 @using (Html.BeginForm("xyz", "xyz", FormMethod.Post))
 {
      @Html.TextBoxFor(x => x.Email)

which results in the input box not being editable for some reason.

I'd prefer to do something more like

 ReactDOM.render(
      <form><input type="text" data-val="@Model.datannotations[1].val" /></form>

Is that possible? How does one get the data-val values from the model anyway? What is the best way to achieve this?

like image 460
totalnoob Avatar asked Aug 25 '16 18:08

totalnoob


People also ask

Can we do validation in MVC using data annotations?

In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.

How does data annotation help with model validation?

We can easily add validation to our application by adding Data Annotations to our model classes. Data Annotations allow us to describe the rules we want applied to our model properties, and ASP.NET MVC will take care of enforcing them and displaying appropriate messages to our users.

What is data annotation in MVC?

DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of . NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations.


1 Answers

it should not be possible.

These are two differents ways to delvelop the ui. The razor way is preprocessing the markup code in server side to fill it.

And react works in another flow using the lifecycle methods, you should have already loaded the data-anotations values for accessing it on render.

Therefore, to make this works you have to run razor engine first to fill the markup and next using react engine. I don't recommend use this approach because it's too hard to develop on it and the developers team have to keep that flow in mind while they are developing

Note this

ReactDOM.render(<ComponentMustHaveJSX/>)
like image 142
guiwme5 Avatar answered Oct 10 '22 04:10

guiwme5