Is there a way to incorporate @Html.ValidationMessageFor into every element within a collection?

Is there a way to include @Html.ValidationMessageFor() for each item in a collection? Let's take an example,

public class FooVm
{
  // some property
  public ICollection<BarVm> Bars { get; set; }
}

public class BarVm
{
  // some property
  [Range(1, int.Max, ErrorMessage = "Must be greater than 1")
  public float? Fox { get; set; }
}

Now, when working with a view,

@model namespace.here.FooVm

<div class="container"></div>
<a href="#" class="trigger">Populate</a>

<script>
$(function() {
  var i = 0;
  var populate = function() {
    var strBuilder = '<input type="text" name="Bars[i].Fox" />';
    $(".container").append(strBuilder);
    return false;
  };

  $(".trigger").click(populate);
});
</script>

Everything seems to be functioning correctly. However, is there a way to add validation to each textbox? I'm still learning ASP.NET MVC 4 and currently using unobtrusive validation for client-side validation. Any recommendations or sample code on how to achieve this would be greatly appreciated. Thank you.

Answer №1

Indeed, the proper way to utilize MVC is not by using Javascript to populate a View. Instead, you can render all textboxes in this manner:

To begin with, here's the class code:

public class FooVm
{
    // some property
    public List<BarVm> Bars { get; set; }

    public FooVm()
    {
        // Ensure the collection exists to avoid NullReferenceException
        this.Bars = new List<BarVm>();
    }
}

public class BarVm
{
    // some property
    [Range( 1, Int32.MaxValue, ErrorMessage = "Must be greater than 1" )]
    public float? Fox { get; set; }
}

Next, the code for the View:

@model WebApplication2.Models.FooVm

<h2>Sample View</h2>

@using ( Html.BeginForm( "YourAction", "YourController" ) )
{
    <div class="container">

    @for ( int i = 0; i < Model.Bars.Count; i++ )
    {
        @Html.TextBoxFor( m => m.Bars[i].Fox )
        @Html.ValidationMessageFor( m => m.Bars[i].Fox );
    }

    </div>
}

This approach will generate the necessary tags along with the validation message components. In addition, you can consolidate all error messages in one location by utilizing

@Html.ValidationSummary()

If displaying the content only upon clicking a button is preferred, consider employing a partial view and loading it instead. This method is more favorable compared to manually creating tags and attributes for validation using javascript.

Best regards,

Eleanor

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React is displaying [object Object] instead of the intended value on the webpage. What steps can be taken to resolve this issue?

I have attempted to retrieve data from an API and am currently working on displaying this data within a table cell inside a component. Instead of rendering the original data, React is displaying [object Object]. I tried using the join() method with commas ...

Apply a uniform style to a selection of <a> tags using CSS

As a beginner in web programming, I am currently exploring ASP.NET. In my project, I have three links structured like this: <ul style="margin-top:10px;"> <a style="background-color:transparent;padding:0px;" href="..."><img src="..."/> ...

ClickOnce deployment software

Our software requires an updater functionality. While considering using "ClickOnce", I discovered that the ClickOnce deployer restricts writing information to the registry. Is it possible to utilize ClickOnce solely for the updater tool without the deploym ...

Is it possible to display data on a webpage without using dynamic content, or do I need to rely on JavaScript

Imagine a scenario where I have a single-page website and I want to optimize the loading time by only displaying content below the fold when the user clicks on a link to access it. However, I don't want users with disabled JavaScript to miss out on th ...

Having trouble with autocompleting using jquery json and getting an Internal Server Error 500?

Why does the autocomplete program with jQuery JSON and C# work on local but not on the server? [WebMethod] public List<string> GetAutoCompleteData(string prefixText) { ... Here is the error: Internal server error 500 In addition to that, an ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...

Having issues installing Parcel through npm - Encountered an error while parsing package.json information

After creating a package.json file using the command npm init in my project folder, I proceeded to run npm i parcel --save-dev which resulted in an error message: C:\Users\XPRESS\Desktop\starter>npm i parcel --save-dev npm ERR! code ...

Enhance your website's user experience with dynamic zoom functionality using Javascript

Currently, I am in search of a javascript zoom library that functions similarly to this one. However, the majority of options available require the presence of thumbnails images for the unzoomed image, which is proving to be quite bothersome for me as I on ...

A guide to utilizing client-side scripts on a button click event in order to adjust the content of a

Currently, I am working on developing an interface utilizing ASP.NET in combination with AJAX Webforms. The page includes an update panel that appears when the page is initialized and after certain actions are taken to authenticate the user using a PIN num ...

Tips on customizing data labels using Jquery Highcharts in column charts

Is there a way to change the positioning of data labels in a column chart? Currently, my data labels appear within the columns, but I'd like to adjust their position. I've tried changing the code below, but nothing seems to work. The colors chang ...

Using browserify with html2canvas is causing compatibility issues

When I initially tested html2canvas as a standalone script, it worked perfectly. However, when attempting to use the npm package version, it is proving to be quite uncooperative. Essentially, it does not execute any actions or trigger the then function. T ...

Creating a hybrid SPA with Partial Views for select pages and a RenderBody method for the rest

I am in the process of converting my MVC 4 (Razor) app into more of a SPA single page application. While it is not purely a SPA, with 5 pages utilizing Ajax to load content in the body section, I also have one-off pages that do not require Ajax. Everythin ...

Derive the property type based on the type of another property in TypeScript

interface customFeatureType<Properties=any, State=any> { defaultState: State; properties: Properties; analyzeState: (properties: Properties, state: State) => any; } const customFeatureComponent: customFeatureType = { defaultState: { lastN ...

Displaying an array result as 'object object'

Apologies if my explanation is confusing, but I am currently dealing with an array object and trying to extract the fields for output. However, all I seem to be getting is [object object] $.getJSON( "https://service1.homepro.com/smart.asmx/GetFAP_ProfileR ...

Upon updating from dotnet v2 to v8, an error has appeared stating "System.MissingMethodException"

While working with my backend in C# and frontend in Angular, I encountered an error after upgrading dotnet to version 8. The error occurs when trying to login through the frontend: System.MissingMethodException: 'Method not found: 'Void CoreTy ...

What causes the browser to be blocked when using $.getJSON()?

Managing a page that lists hardware devices monitored for customers can be challenging, especially when considering the status of each device. To avoid slow page load times, I have implemented a strategy where the device list is displayed first, and then t ...

Typescript inheritance results in an undefined value being returned

I am trying to understand the code below, as I am confused about its functionality. In languages like C# or Java, using the base or super keyword usually returns values, whereas in TypeScript, I am receiving "undefined". However, when I switch from using " ...

Is it possible to fetch the accessor name from the column header in react-table?

My columns are defined as: const columns = React.useMemo( () => [ { Header: "Name", accessor: "name", // accessor acts as the "key" in the data }, { Header: ...

refreshing a react component when new props are received

Looking for a solution involving a React Native Component that requires an image URI as a prop? The prop is passed from another js file using the code snippet below: <SlideComponent imageUri={listOfAssets[counter].uri} /> The approach of passi ...

Exploring the world of Restify: Mastering the art of sending POST

Having trouble reading the body of a request while trying to create an API with Restify. Snippet from main.js: 'use strict'; const perfy = require('perfy'); perfy.start('startup'); const restify = require('rest ...