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?