Pass various arrays from JavaScript interface to C# MVC method

How can I input items (selectedPublishersList, selectedTranslatorsList, selectedAuthorsList) in this action? I have tried to pass the data from the view to the action, but the received value is always null in the controller.

C#


[HttpPost]
public async Task<ActionResult> Create(CreateBookViewModel model)
{
    var bookCategory = await _bookCategoryService.GetById(model.CategoryId);
    var selectedAuthors = Request.Form["selectedAuthors"].ToString();
    var selectedPublishers = Request.Form["SelectedPublishers"].ToString();
    var selectedTranslators = Request.Form["SelectedTranslators"].ToString();

    //model.CategoryId = CategoryId;
    model.Category = bookCategory.Name;
    model.Authors = selectedAuthors.Split(',').ToList();
    model.Publishers = selectedPublishers.Split(',').ToList();
    model.Translators = selectedTranslators.Split(',').ToList();

    if (ModelState.IsValid)
    {
        var result = await _bookService.Create(model);
        if (result.IsSucceeded)
        {
            return RedirectToAction("Index", result);
        }
        else
        {
            ModelState.AddModelError(string.Empty, "خطا در ایجاد کتاب.");
        }
    }
    //return View(model);
    return RedirectToAction("Create");
}

I attempted to use hidden inputs, but I was unable to retrieve the data in the action due to my limited knowledge of javascript.

HTML


<!-- HTML code goes here -->

In this particular code snippet, I made an effort to add values for each list. If duplicates are encountered, an error message will be displayed. Deleted items can also be added back, and the recorded data will be sent to the action in C#.

JavaScript


// JavaScript code goes here

Answer №1

Certainly consider making a small change to your updateHiddenFields() function by updating var selectedAuthors to var SelectedAuthors, like this:

function updateHiddenFields() {
    var SelectedAuthors = selectedAuthors.join(",");
    var SelectedPublishers = selectedPublishers.join(",");
    var SelectedTranslators = selectedTranslators.join(",");

    console.log("SelectedAuthors: " + SelectedAuthors);
    console.log("SelectedPublishers: " + SelectedPublishers);
    console.log("SelectedTranslators: " + SelectedTranslators);

    document.getElementById("SelectedAuthors").value = SelectedAuthors;
    document.getElementById("SelectedPublishers").value = SelectedPublishers;
    document.getElementById("SelectedTranslators").value = SelectedTranslators;
}

This will make sure that all the necessary data is correctly updated.

In addition, consider resetting the ModelState and executing TryValidateModel in your scenario as follows:

...
model.Translators = selectedTranslators.Split(',').ToList();
ModelState.Clear();
TryValidateModel(model);
if (ModelState.IsValid)
...

This method can help ensure the accuracy of your model's state.

https://i.sstatic.net/8BiEs.png https://i.sstatic.net/xtbwC.png

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

Is there a way to retrieve the height of a document using vh units in jQuery?

$(window).scroll(function() { $scrollingDiv.css("display", (($(window).scrollTop() / 100vh) > 0.1) ? "block" : ""); }); Is there a way to change the unit $(document).height()) > 0.1) to use 100vh instead? I'm still learning jQuery and would ...

Playback on iPhone devices and Safari experiences a 50% reduction with AudioWorklet

I recently developed a basic audio recorder that utilizes the AudioWorkletAPI. While the playback functions smoothly on Chrome, it seems to have issues on Safari and iPhone devices (including Chrome on iPhone) where half of the audio is missing. Specifical ...

Issues with AngularJS email validation specifically related to domain names are causing errors

Hello, I'm currently working on an AngularJS application where I'm implementing email validation. I'm facing an issue where I expect an error message to appear when I enter 'test@test', but it's not working as intended. Here ...

My code seems to be malfunctioning, do you see any issues with it?

When attempting to display blog data based on email, the following code line displayed an error cannot GET /myblog: app.get("/myblog/:e_mail", async (req, res) => { const requestedEmail = req.params.e_mail; try { const user = await Use ...

Creating diverse content for various tabs using JavaScript

I have developed a code that uses a for loop to generate tabs based on user input. var tabs = ""; var y = 1; for (var x = 0; x < tabNum; x++) { tabs += "<li class = 'tabbers'>" + "<a href='#tab'>Tab</a>" + "& ...

The withRouter function in React Router does not automatically inject the router

Desiring to implement withRouter on my primary React component named 'App'. You can view the documentation here. This is how I utilize it: import React from "react"; import { render } from "react-dom"; import {Router, Link, hashHistory, Rout ...

Retrieving Controller Data in AJAX Response with Rails 5

After researching numerous articles on this topic, I find myself more confused than enlightened. The various approaches to the same task in Rails have left me feeling overwhelmed. The traditional method of handling AJAX calls involves: JavaScript listeni ...

An illustration of React's "component did mount" in JavaScript is shown in this example

As I embark on my journey with React, I find myself exploring code examples and stumbling upon an interesting discovery. You can find the link to the React tutorial here. Below is a snippet of code from the lifecycles section; componentDidMount() { this.t ...

Creating a communication bridge between a Chrome extension and an Angular application on a webpage

There's a chrome extension I've been working on that alters the Dom of webpages. However, I'm dealing with a page built in Angular, which means I need to adjust the scope of the element. How would I go about doing this? ...

Jumping over loop iteration following a JavaScript catch block

Currently, I am developing an API that requires making repeated calls to another API (specifically, Quickbooks Online) within a loop. These calls are encapsulated in promises that either resolve or reject based on the response from Quickbooks. Everything f ...

CSS transition fails to revert

My standard opacity animation is not working in reverse order. Here is a link to the JSFiddle example. According to the documentation, it should work automatically. Since I am new to JavaScript, I am unsure if this issue lies in my code or if the CSS anima ...

Switching from JavaScript to TypeScript resulted in React context not being located in its respective file

I previously had my context and context provider set up in a file, and everything was working perfectly. However, I recently decided to convert all of my files to TypeScript, including this one. Unfortunately, I've encountered a strange issue that I c ...

What is the reason for function components running in multiples of 2 when the state changes?

I need help with a React question that I can't quite figure out. I have a component where new data keeps getting added to the existing data. Initially, it makes sense for two console logs to appear due to Mount and Update. But after that, why do 4 con ...

React and TypeScript are not in sync: Expecting 0 arguments, but receiving 1 in a useReducer function

Greetings! I'm currently facing some challenges while trying to implement a useReducer in a TypeScript application. I have encountered several errors (all related to the reducer), but one error stands out as the most common throughout the entire app. ...

Recording JavaScript Cookie Visit Counts and Tracking Last Login Dates

I am a beginner in JavaScript and cookies, and I am attempting to create a cookie that can show the number of times someone has visited a website, the date of their last visit, and the expiration date of the cookie. Initially, I tried modifying code from ...

Create a list using ng-repeat in AngularJS, each item separated by "custom categories"

I am looking to create a dynamic list that will display values entered by users, categorized by custom categories. The challenge is that I do not know in advance which category each element will belong to. Here's an example of how I envision the list ...

What is the best way to duplicate a value and save it in an array?

I have a calendar and I want to be able to copy the selected day's value and store it in an array. Then, if another day is clicked, I would like to add the current day's value along with the previous day's value to the array. Users should be ...

What are the best strategies for eliminating element cloning and duplication in Vue?

As a novice programmer, I've developed a web app similar to Trello. It allows users to create boards and within those boards, lists can be created. Each list is displayed uniquely with different IDs. However, the list items are displayed with the same ...

Determine whether the current page was reached by pressing the back button

Can we determine if the current page was loaded via a back button press? Here is the scenario: index.html (contains a link to page1 in the menu) page1.html (loads content from ajax with a link to page2) page2.html (user presses the BACK button) page1.h ...

Clicking on a button in the Shield UI Grid Toolbar will apply filters to

Currently, I am working with a grid that utilizes a template for the toolbar. In this grid, there is a column labeled "Status." My goal is to filter the rows so that only those where the Status equals Request to Reschedule, Cancelled, Office Call Required, ...