1

I have this code that is not running in asp.net core 3.1 I need to send a variable to the method GetClientCaseType() it give error in @Model.GetClientCaseType[myInt] myInt if i put 1 or any number it works fine while for variable it give error

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; 
}

Any Solution please help thanks in advance

mj1313
  • 7,930
  • 2
  • 12
  • 32
Ahmad Zrein
  • 11
  • 1
  • 1

2 Answers2

0

Actually, you can't do this. The reason is that they do not "live" in the same time. Javascript code is available only after C# / Razor is rendered. Refer to this thread.

So, I think you should use ajax here to send a request to access GetClientCaseType() method.

Update:

For how to send a ajax post request, you need to do the below steps:

1.Add the below 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());
},

This is 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);
    }
}

Note: the pagehandler should be in this format OnPostXxx() or OnGetXxx().

And the url in ajax should like XXX?handler=Xxx.

Result:

enter image description here

mj1313
  • 7,930
  • 2
  • 12
  • 32
0

I tried ajax with no result '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>
Ahmad Zrein
  • 11
  • 1
  • 1