How I Can send question and answer by without reload web page

49 views Asked by At

I want send qusetion to server and the then the server answer my quserion , and Iwant show the previous question s and answers , basd on the search.htmlcs

@* @page
@model SearchModel
@{
    ViewData["Title"] = "Search Document";
}

<div class="text-lg-start header">
    <h3>Search your documents</h3>
</div>

<div class="main-container">
    <div class="chat-container" id="chatContainer">
        @foreach(string key in Model.ConversationHistory.Keys)
        {
            @if(key == "userInput")
            {
                <div class="user-message">@Model.ConversationHistory[key]</div>
            }
            else
            {
                <div class="bot-message">@Model.ConversationHistory[key]</div>
            }
        }
    </div>
    <form method="post" id="chat-form">
        <div class="textbox-container">
            <input type="text" name="chatInput" id="chatInput" class="form-control" placeholder="Type your message...">

            <button type="submit" class="chat-button" title="Chat">
                <i class="fas fa-comment"></i> <!-- Chat icon -->
            </button>
        </div>
    </form>

</div> *@



@page
@model SearchModel
@{
    ViewData["Title"] = "Search Document";
}

<div class="text-lg-start header">
    <h3>Search your documents</h3>
</div>

<div class="main-container">
    <div class="chat-container" id="chatContainer">
        @foreach (var message in Model.ConversationHistory)
        {
            <div class="@(message.Key == "userInput" ? "user-message" : "bot-message")">@message.Value</div>
        }
    </div>
    <form id="chat-form">
        <div class="textbox-container">
            <input type="text" id="chatInput" class="form-control" placeholder="Type your message...">

            <button type="submit" class="chat-button" title="Chat">
                <i class="fas fa-comment"></i> <!-- Chat icon -->
            </button>
        </div>
    </form>
</div>

@section Scripts {
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="~/Chat.js"></script> <!-- Include your JavaScript file here -->
}

The problem when I send my qusetion the web page reload and show the last question and answer, without previous questions and answers Cox reload web page properties.

I used the Ajax-Query but I think I have problem beacuse when I created my project I difn't use Controller the back-end code in the search.htmlcs.cs

using AzOpenAIChatDemo.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Text.Json;
using AzOpenAIChatDemo.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace AzOpenAIChatDemo.Pages
{
    public class SearchModel : PageModel
    {
        private readonly IAzOpenAIService _azOpenAIService;
        private readonly ILogger<SearchModel> _searchLogger;

        public Dictionary<string, string> ConversationHistory { get; set; } = new Dictionary<string, string>();


        

        public SearchModel(IAzOpenAIService azOpenAIService, ILogger<SearchModel> searchLogger)
        {
            this._azOpenAIService = azOpenAIService;
            this._searchLogger = searchLogger;
        }

        public void OnGet()
        {
        }

        public async void OnPost(string chatInput)
        {
            ConversationHistory.Add("userInput", chatInput);

            var response = _azOpenAIService.GenerateTextAsync(chatInput);
            var content = response.Result.Value.Choices[0].Message.Content;

            StringBuilder sb = new StringBuilder();
            sb.Append("\n\n\n");
            sb.Append(content);
            sb.Append("\n\n\n");

            ConversationHistory.Add("chatResponse", sb.ToString());
        }
    }




}
1

There are 1 answers

0
Jalpa Panchal On

You could use the OnPost handler to return a JsonResult (or IActionResult) and use client-side JavaScript to send the AJAX request and handle the response.

OnPost method:

public async Task<JsonResult> OnPostAsync(string chatInput)
{
    ConversationHistory = HttpContext.Session.GetObjectFromJson<Dictionary<string, string>>("ConversationHistory") ?? new Dictionary<string, string>();
    
    ConversationHistory.Add("userInput", chatInput);
    
    var response = await _azOpenAIService.GenerateTextAsync(chatInput);
    var content = response.Value.Choices[0].Message.Content;

    StringBuilder sb = new StringBuilder(content);
    
    ConversationHistory.Add("chatResponse", sb.ToString());

    HttpContext.Session.SetObjectAsJson("ConversationHistory", ConversationHistory);
    
    return new JsonResult(new { UserMessage = chatInput, BotMessage = sb.ToString() });
}

Session extension methods to handle object serialization:

public static class SessionExtensions
{
    public static void SetObjectAsJson(this ISession session, string key, object value)
    {
        session.SetString(key, JsonSerializer.Serialize(value));
    }
    public static T GetObjectFromJson<T>(this ISession session, string key)
    {
        var value = session.GetString(key);
        return value == null ? default : JsonSerializer.Deserialize<T>(value);
    }
}

javascript code:

$(document).ready(function () {
    $('#chat-form').submit(function (e) {
        e.preventDefault();
        var chatInput = $('#chatInput').val();  
        $.ajax({
            type: 'POST',
            url: '/Search', 
            data: { 'chatInput': chatInput },
            success: function (response) {
                $('#chatContainer').append('<div class="user-message">' + response.UserMessage + '</div>');
                $('#chatContainer').append('<div class="bot-message">' + response.BotMessage + '</div>');
                $('#chatInput').val('');
            }
        });
    });
});

Add the code to enable session state and configure session middleware in startup or program file.