Learn how to execute a method with a dynamic variable in JavaScript

I am currently facing an issue with some code in asp.net core 3.1. I need to pass a variable to the method GetClientCaseType(). An error is thrown when using @Model.GetClientCaseType[myInt], where myInt works fine when set to a specific number, but throws an error when set as a variable.

function casetype(value) 
{ 
   var myInt = parseInt(value.options[value.selectedIndex].value); 
   var casetype |"= '@Model.GetClientCaseType[myInt]'; 
   alert(casetype + ' = ' + myInt.toString()); 
   $("#ClientCase_cCaseType").val(casetype);
}

in .cs page

public string GetClientCaseType(int? myInt) 
{ 
   return something; 
}

If you have a solution, please help. Thank you in advance.

Answer №1

I attempted to use ajax but encountered an 'error'

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebLawyer1.Data;
using WebLawyer1.Models;

namespace WebLawyer1.Pages.ClientCases
{
    public class CreateModel : PopulateClientCasePageModel
    {
        private readonly WebLawyer1.Data.LawyerDbContext _context;

        public CreateModel(WebLawyer1.Data.LawyerDbContext context)
        {
            _context = context;
        }

        public IActionResult OnGet()
        {
            PopulateClientInfosDropDownList(_context);
            PopulateCaseTypesDropDownList(_context);
            return Page();
        }

        [BindProperty]
        public ClientCase ClientCase { get; set; }

        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        {
            //if (!ModelState.IsValid)
            //{
            //    return Page();
            //}

            //_context.ClientInfo.Add(ClientInfo);
            //await _context.SaveChangesAsync();

            //return RedirectToPage("./Index");

            var emptyClientCase = new ClientCase();

            if (await TryUpdateModelAsync<ClientCase>(
                 emptyClientCase,
                 "clientcase",   // Prefix for form value.
                s => s.iClientInfoID, s => s.iCaseTypeID, s => s.cCaseType, s => s.cPart,
                s => s.iSequence, s => s.cKeyCase, s => s.dDate, s => s.cTitle,
                s => s.cNote, s => s.cDetail, s => s.nFees, s => s.lWinFail, s => s.lClosed))

            {
                _context.ClientCase.Add(emptyClientCase);
                await _context.SaveChangesAsync();
                return RedirectToPage("./Index");
            }

            // Select CategoryID if TryUpdateModelAsync fails.
            PopulateClientInfosDropDownList(_context, emptyClientCase.iClientInfoID);
            PopulateCaseTypesDropDownList(_context, emptyClientCase.iCaseTypeID);
            return Page();
        }

        public ActionResult GetUploadedFile(int id)
        {

            var result = _context.CaseType.Where(x => x.iCaseTypeID == id).First();


            return Json(result.cCaseType);
        }
    }
}
<script>
function casetype(value) {
    var id = parseInt(value.options[value.selectedIndex].value);
       $.ajax({
        url: '@Url.Action("GetUploadedFile", "Create")',
             type: "POST",
             data: JSON.stringify(id),
             contentType: "application/json",
             datatype: "json",
             success: function (data) {
             if (data != null) {
                var vdata = data;
                $('#ClientCase_cCaseType').val(vdata.id);
        }
    }
});
    }
</script>

Answer №2

Unfortunately, it's not possible to achieve this because JavaScript code is only available after C# / Razor has been rendered. You can find more information about this on this thread.

My suggestion would be to use ajax to send a request to access the GetClientCaseType() method.

Update:

If you want to send an ajax post request, follow these steps:

1. Add the following service in stratup.cs

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

2. Add the AntiForgeryToken to the current page

@Html.AntiForgeryToken();

3. Set the token to request header in ajax

beforeSend: function (xhr) {
    xhr.setRequestHeader("XSRF-TOKEN",
        $('input:hidden[name="__RequestVerificationToken"]').val());
},

Here's an example:

Create.cshtml:

@page
@model RazorApp.Pages.ClientCases.CreateModel

@Html.AntiForgeryToken();


<button id="btn" onclick="casetype()">Click</button>

@section scripts{

    <script>
        function casetype() {
            var id = 1;
            $.ajax({
                url: 'Create?handler=GetUploadedFile',
                type: "POST",
                data: { id : id },
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                success: function (data) {
                if (data != null) {
                    var vdata = data;
                }
                }
            });
        }
    </script>
}

Create.cshtml.cs:

public class CreateModel : PageModel
{
    public void OnGet()
    {
    }

    public IActionResult OnPostGetUploadedFile(int id)
    {
        var result = "AAA";
        return new JsonResult(result);
    }
}

Please note that the page handler should be in the format OnPostXxx() or OnGetXxx().

Also, make sure the url in ajax follows the format XXX?handler=Xxx.

Result:

https://i.sstatic.net/jFVaW.gif

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

Combining Multiple Properties in a Single-File Component with Vue.js 2

Currently, my project involves Laravel 5.5 & Vue.js 2.x. After extensive research and seeking answers, I began working with components. However, I am encountering a warning message upon page rendering: [Vue warn]: Property or method "trimestral" is not def ...

How can I make a recently added row clickable in an HTML table?

I have a table where each row is given the class ".clickablerow". I've set up an onclick function so that when a row is clicked, a dialog box appears allowing me to insert text above or below as a new row. The issue I'm facing is that even though ...

Is a JavaScript variable automatically global if not declared with var?

Here is the code snippet from one of my files: function refreshGridSuccess(responseText, entity) { oTable = $('#dataTable').dataTable({ "sScrollX": "100%", In a different file, I have the following code: $('#d ...

What is the method for extracting CSS class names and storing them in an array using PHP?

Hey there, I have a bunch of CSS code and I'm looking for a way to extract only the names of the CSS classes without the unnecessary characters and values, and then store them in an array using PHP. For Example: .dungarees { content: "\ef ...

Cancel your subscription to a PubNub channel when the unload event occurs

Currently, I am developing a multiplayer game in Angular utilizing the PubNub service along with the presence add-on. One of the challenges I am facing is detecting when a player unexpectedly leaves the game. This is crucial for sending notifications to o ...

I am curious to know why my jQuery when().then() function is firing before the completion of the ajax request in the when clause

I have a situation where I need to set an async callback because a function is fetching content from a remote location. Here's what I am currently doing: $.when( priv[box.view.renderWith](content, box.view.gadget_id) ).then(function(late) { conso ...

using a conditional operator to show an image in a gridview

When the value of ImageUrl='<%# "~/ProductImageHandler.ashx?Id="+ Eval("Id") %>' is null, I want to display a dummy image from a folder that I will place in the project. How can I achieve this? <asp:Image ID="imgProduct" Width="200px" r ...

Upon encountering an expression, the code anticipated either an assignment or a function call, but instead found an expression, triggering the no

When using the forEach method within a function in JavaScript, I encountered a code compilation failure with the following error: Expected an assignment or function call and instead saw an expression no-unused-expressions. This error occurs for both ins ...

jQuery swap- enhancing the appearance of numerical values

I am looking to customize specific characters within my <code> tag. While searching online, I came across the .replace() function but encountered issues when trying to style numbers. My goal is to change their appearance without altering the text its ...

Strategy for refreshing a Polymer application

Our application is a Polymer 2 single-page app that incorporates custom build steps to create versioned resource files using gulp-rev-all. Everything is functioning properly, but we are now looking to implement a secure way of refreshing the application. C ...

Switch between hiding and showing a DIV element

Struggling to toggle a DIV (hide and show) when the 'commentDIV' button is pressed? Despite my efforts, I haven't been able to make it work so far. Below is my HTML code. My goal is to hide/show a specific DIV block only when its associated ...

Creating a function to update data in a Node.js/MongoDB environment

Hey there! I'm new to working with nodejs and mongodb, and I'm trying to create a function that updates the win, lose, and draw record in my UserSchema. Here's my Schema: UserSchema = new mongoose.Schema({ username:'string', ...

Upon the publication of the second post, NodeJS will receive a 500

My router code is ready for use var express = require('express'); var router = express.Router(); function sendSolve(test) { // Some code for calculations } /* POST listing. */ router.post('/', function (req, res, next) { send ...

Utilizing ASP.NET Identity 2 to allow for the separation of Email and UserName, with the added convenience of using

Initially, ASP.NET Identity is set up to have the UserName and Email fields as the same value entered by the user. I have customized my system to have distinct username and email inputs for each user. However, I am facing an issue where I am unable to log ...

Struggling to retrieve data from supabase in order to create a photo gallery, only to encounter the error message "Result is not iterable" while using Next JS 13

I am currently utilizing Next JS 13 and have a table on supabase that I would like to use to create a gallery with my images. Here is the code snippet from app/products/page.tsx: import { createClient } from '@supabase/supabase-js'; import Galle ...

The latest version of Next.js, Version 12, encounters an issue with theme-ui that results in the error message "code: 'ERR_REQUIRE_ESM'"

Encountering an error while working with Next.js 12 after creating a theme using theme-ui. https://i.stack.imgur.com/BtH7W.png Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\fm-nextjs\node_modules\@mdx-js\react\ind ...

If a div is hidden, disregard this particular CSS rule

In my current scenario, I am dealing with 3 distinct divs: - Menu - Header (#rt-top-surround) - Showcase (#rt-showcase) - Main Body content (#rt-mainbody-surround) The Menu is set as 'sticky' with position: fixed. As a result, I have to adjust ...

Is there a way to ensure that this ajax code functions seamlessly with all types of HTML files?

Currently, I am facing a challenge with an ajax call that retrieves data from a database, which I need to load into an HTML file. The issue lies in the fact that I have various HTML files and I am unaware of their contents. Despite spending countless hour ...

Surprising Behavior of React's OnClick Event

Custom Component function ProductCard ({image, name, stats, id}){ let dispatch = useDispatch() let quantity = 1 return ( <> <div className="product-card" ...

Perform a task upon clicking the JavaScript menu

Implementing dropdown menu items using a text link with JavaScript and CSS. You can view a demo here. I am looking to trigger an action when each menu item is clicked. Currently, they are not behaving as expected. HTML: <span class="inline-dropdown- ...