Submitting Data in an Asp.NET MVC 5 Application Using JavaScript and ViewModel

The issue at hand is this: I am utilizing CKEditor for a blog post interface and it provides the word count. However, I need to clean up this data using client-side JavaScript before passing it into the database to track the number of words in each post.

Within my post viewmodel:

public class NewStoryViewModel
{
    [Required]
    public string Title { get; set; }

    [Required]
    public string Content { get; set; }

    [Required]
    public int Genre { get; set; }
    public IEnumerable<Genre> Genres { get; set; }

    [Required]
    public int StoryType { get; set; }
    public IEnumerable<StoryType> StoryTypes { get; set; }

    public int WordCount { get; set; }

    [Required]
    public int StoryAgeRange { get; set; }
    public IEnumerable<StoryAgeRange> StoryAgeRanges { get; set; }

    [Required]
    public int Visibility { get; set; }
    public IEnumerable<Visibility> Visibilities { get; set; }
}

And within the post controller:

[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult New (NewStoryViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var newStory = new Story
        {
            AuthorId = User.Identity.GetUserId(),
            Title = viewModel.Title,
            Content = viewModel.Content,
            GenreId = viewModel.Genre,
            StoryTypeId = viewModel.StoryType,
            StoryAgeRangeId = viewModel.StoryAgeRange,
            VisibilityId = viewModel.Visibility,
            CreatedAt = DateTime.Now,
            WordCount = viewModel.WordCount
        };

        dbContext.Stories.Add(newStory);
        dbContext.SaveChanges();

        return RedirectToAction("Index", "Story");
    }
    else
    {
        return View(viewModel);
    }
}

In the razor view on the client-side, the following script exists:

$(document).ready(function () {

    $('#addStoryBtn').on('click', function () {
        var wordcount = $('#cke_wordcount_Content').html();
        var slicedWordCount = wordcount.slice(6);
        var trimmedWordCount = slicedWordCount.trim();
        var indexOfSlash = trimmedWordCount.indexOf("/");
        var finalWordCount = trimmedWordCount.slice(0, indexOfSlash);

        //Ajax call commented out here for brevity

    });
});

What's happening is that CKEditor displays the word count like this:

Words: 4/5000

So, using some JavaScript, I extract just the number before the slash.

However, when attempting to pass this data through ajax, it returns as 0. One solution I considered was using a hidden field in the view:

@Html.Hidden(new  { WordCount = finalWordCount })

But an error is thrown stating that finalWordCount is undefined in the current context since it is tied to the button click event. Any recommendations on how to successfully transfer the word count to the viewmodel?

Answer №1

In the comments, you mentioned encountering a 500 internal server error, possibly after attempting to address the invalid JSON as suggested by Shyju. It seems likely that you're facing difficulty debugging the controller action because it requires an anti-forgery token to be included in the POST request body.

To resolve this issue, consider implementing the following solution:

var form = // choose the appropriate selector for your form
var token = $('input[name="__RequestVerificationToken"]', form).val();

$.ajax({
  url: "/story/new",
  type: 'POST',
  data: {
      __RequestVerificationToken: token,
      WordCount: finalWordCount
  },
  success: function (data) {
      console.log("Success")
  },
  error: function (error) {
      console.log("An error occurred: " + error);
  }
});

By incorporating this code snippet, you should be able to resolve the validation error and proceed with executing the action successfully.

Answer №2

If you are working with an MVC application, it is likely that the expected request body format is JSON, which is the default setup for asp.net MVC. Therefore, before sending data to the server, make sure to convert the model into a valid JSON string.

Here is an example of how you can do this:

var data = JSON.stringify({WordCount: finalWordCount});
$.ajax({
     url: "/story/new",
     type: 'POST',
      data: data,
      success: function (data) {
          console.log("Success")
      },
      error: function (error) {
          console.log("error is " + error);
      }
    })

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

Reinitialize the nested property of an object in JavaScript

I've encountered an issue while using the Vue3 composition API where attempting to reset a form with nested properties using Object.assign does not work as expected. const initialForm = { name: "", details: { type: "" } }; const f ...

Navigating with React Router: Maintaining user data persistence during route changes

As I develop a React Router application, my focus is on mastering authentication. Here is an overview of the key components: Login component (login.jsx) Verifies user credentials on the backend Saves the authentication token in local storage Returns t ...

RxJS - Only emit if another source does not emit within a specified time frame

Imagine having two observables. Whenever the first one emits, there should be a 2-second pause to check if the other observable emits something within that timeframe. If it does, then no emission should occur. However, if it doesn't emit anything, the ...

Convert JavaScript object into distinct identifier

I have a data object where I'm storing various page settings, structured like this: var filters={ "brands":["brand1","brand2","brand3"], "family":"reds", "palettes":["palette1","palette2","palette3"], "color":"a1b2" }; This object is ...

Exploring the World of Auditing using C# and .NET

Managing user actions on my web application is a priority for me. I need to keep track of login attempts, database insertions and updates, exceptions thrown, and more. A senior colleague recommended using a queue system to speed up performance. By simply ...

Having trouble sending an array from Flask to a JavaScript function

As a newcomer to web development and JavaScript, I'm struggling to pass an array from a Flask function into a JavaScript function. Here's what my JS function looks like: function up(deptcity) { console.log('hi'); $.aja ...

Showing Progress bar in Django view during video download using youtube-dl

When a button is clicked, I make an AJAX call to 'search/'. My goal is to display the details {"file_name":d['filename'],"percentage":d['_percent_str'],"speed":d['_eta_str']} in a progress bar on a webpage while down ...

Maximizing your efficiency with Selenium elements: waiting, checking, and clicking without the need to find the elements again

I'm a beginner with Selenium and previously used Telerik's free testing framework. I'm struggling to understand how to interact with elements that have already been identified using [FindsBy]. For example: [FindsBySequence] [Finds ...

How can one continue repeating a series in async.js until an unforeseen error arises?

Is it possible to continuously execute a series of tasks in async.js until an unexpected error occurs? For example: async.series([ function(callback) { // perform task }, function(callback) { // perform another task }, ...

Convert web address object to URL string

Currently, I am dealing with a stringified object stored in my localStorage, const stringifiedURLObject = fromLocalStorage I have attempted to parse this string using JSON.parse to obtain a normal Url Object. Now, I am looking to convert this object int ...

Surprising outcomes when working with JavaScript date and time functionalities

Check out the code snippet below: let startDate = new Date(); const lastDate = new Date(); lastDate.setMonth(11,31); const timeArray = []; while(startDate <lastDate){ timeArray.push(startDate); console.log(startDate) startDate =new Date(start ...

Discovering the worth in Meteor MongoDB

As someone who is new to web programming, I have been experimenting with Meteor and MongoDB lately. I have a form that sends data to MongoDB, and by using the query below, I was able to retrieve the most recent entry: database.findOne({}, {sort: {'t ...

JavaScript code to retrieve and store data from API endpoints

I am working with a Web API endpoint that provides the location of a URL (). When a button is clicked, this API is called and a URL is returned. The file format could be PDF, Excel, or Word. I am looking for a way to download the file and save it to disk ...

Unable to reach socket.io.js on Raspberry Pi using Lighttpd [Node.JS & Socket.IO]

I just started learning about Node.JS and Socket.IO yesterday. I've been attempting to set up Node.JS and Socket.IO on my Raspberry Pi, but I can't seem to get it working. I'm unable to access <myip>:1337/socket.io/socket.io.js. I fol ...

Start flicker issue in Vue 3 transition

I have created a carousel of divs that slide in and out of view on the screen. However, I am facing an issue where during the start of each transition, when a new div is rendered (i.e., the value of carousel_2 changes), it appears without the transition-en ...

issue with object passing in RedirectToAction()

I'm currently working on an ASP.NET MVC4 Application that has two partialViews: [HttpGet] public ActionResult Autocomplete_Search(string accountHead, List<LedgerModel> ledge) { if (!String.IsNullOrEmpty(accountHead)) { ledge = (from ...

A guide to loading CSS and JavaScript files asynchronously

Is it possible to use loadCSS (https://github.com/filamentgroup/loadCSS/blob/master/README.md) to allow the browser to asynchronously load CSS and JavaScript? This is what I currently have in my head tag: <link rel="preload" href="http://zoidstudios. ...

Is it possible for the filter with the new date() function to accept formats other than yyyy-mm-dd?

After receiving a response from mydatepicker in the specific format below: { "isRange":false, "singleDate":{ "date":{ "year":2022, "month":5, "day":13 }, "jsDate": ...

The unusual spinning behavior of child elements in three.js

My current project involves implementing an experimental version of a 2x2x2 Rubik's Cube. I have gathered insights from two previous posts that addressed issues related to attaching and detaching child objects in Three.js: Three.js: Proper way to add ...

During the Page_Load event, Nested Accordion Controls are being detected as having a Null value

Within a nested accordion, there exists a dropdownlist that needs to be bound with data on page load. However, the method fails to find the dropdownlist control and treats it as null, causing the page load to break. Below is an example of the relevant code ...