skip to Main Content

I work on asp.net mvc i face issue i can’t auto update reason using java script ajax

auto update meaning when user start writing on reason it will save on database table Automatically based on Request No

update i need will done without using update button it will auto save using java script ajax

my html as below

@model HR.WorkforceRequisition.Models.ResignationRequester
<table style="border: 1px solid 
black;width:100%;">




     <tr>
         <td style="width: 50%; font-weight: bold; padding-top: 10px;">
             <div class="form-group hover">
                 @Html.LabelFor(model => model.RequestNo, htmlAttributes: new { @class = "control-label col-md-5" })
                 <div class="col-md-7" id="RequestNo">
                     @Model.RequestNo
                 </div>
             </div>
         </td>
         <td>
<div class="col-md-7" id="Reason">
                @Html.TextAreaFor(model => model.Reason, new { id = "Reason", @class = "form-control" })
</div>
        </td>

     </tr>
</table>

action name Edit will update on database on ResignationController will be as below

public JsonResult  Edit(ResignationRequester req)
{
    dynamic responseData = new ExpandoObject();
    responseData.success = false;
    responseData.message = "";
    string query;
 
        ResignationRequester workforceRequest = ResignationupdateReason((int)req.RequestNo,req.Reason);
    return Json(responseData);
}

java script function will execute when auto update will be

<script type="text/javascript">
function changereasonbasedonrequestno() {
    console.log("fire event")
    var ResignationRequester = new Object();
    ResignationRequester.RequestNo = document.getElementById("RequestNo").innerHTML.trim();
    ResignationRequester.Reason = document.getElementById("Reason").innerHTML.trim();
}
</script

model used on asp.net mvc will be

public class ResignationRequester
{


    [Display(Name = "Request No")]

    public int RequestNo { get; set; }

    [Display(Name = "Reason")]

    public string Reason { get; set; }
}

confirmation

I need when write any text on reason text area then it will

update it automatically on table based on request no

I don’t need update statement

exactly i need code of java script with ajax request that

will call function Action Edit

2

Answers


  1. I work on asp.net mvc i face issue i can’t auto update reason using
    java script ajax

    auto update meaning when user start writing on reason it will save on
    database table Automatically based on Request No

    How to auto update reason based on request No using JavaScript ajax?

    Well based on your description and scenario, if you want to send update request using ajax without any button click, in that scenario, you need to call javascript event. For instance: OnChange, OnMouseUp.

    Once the user would finish typing the reason, then you should trigger the your javascript function by using the event listener.

    According to your given code snippet, you have to decide when do you want to call ajax. If you want to call ajax soon the user finish typing then you can use @onblur which will call if the cursor loose the focus.

    Apart from the you also can set some delay using setTimeout function, so that every certain interval the ajax will be called.

    But considering the scenario, you can try @onblur which can meet your requirement but you can try other as well.

    Let’s have look in practice, how we can achieve that:

    CSHTML View:

    @model ShoppingCartApp.Controllers.ResignationRequester
    @{
        ViewBag.Title = "Resignation Request";
    }
    
    
    <table style="border: 1px solid black; width:100%;">
        <tr>
            <td style="width: 50%; font-weight: bold; padding-top: 10px;">
                <div class="form-group hover">
                    @Html.LabelFor(model => model.RequestNo, htmlAttributes: new { @class = "control-label col-md-5" })
                    <div class="col-md-7" id="RequestNo">
                        @Model.RequestNo
                    </div>
                </div>
            </td>
            <td>
                <div class="col-md-7" id="Reason">
                    @Html.TextAreaFor(model => model.Reason, new { id = "txtreason", @class = "form-control", @onblur = "updateReason()" })
                </div>
            </td>
        </tr>
    </table>
    

    Javascript:

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script type="text/javascript">
        var timeoutId;
    
        function updateReason() {
            var requestNo = parseInt(document.getElementById("RequestNo").innerHTML.trim());
            var reason = document.getElementById("txtreason").value.trim();
            // console.log(ResignationRequester)
    
            $.ajax({
                url: '@Url.Action("Edit", "JsVariableInCshtml")',
                type: 'POST',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify({ RequestNo: requestNo, Reason: reason }),
                success: function (data) {
                    alert(data.message);
                },
                error: function (error) {
                    console.error("Error updating Reason");
                }
            });
        }
    </script>
    

    Controller:

       [HttpPost]
       public JsonResult Edit([FromBody] ResignationRequester req)
        {
              dynamic responseData = new ExpandoObject();
              responseData.success = false;
              responseData.message = "";
        
              try
              {
                  // Update the Reason in the database
                  ResignationRequester updatedRequest = ResignationupdateReason(req.RequestNo, req.Reason);
        
                  responseData.success = true;
                  responseData.message = "Reason updated successfully";
              }
              catch (Exception ex)
              {
                  responseData.message = "Error updating Reason: " + ex.Message;
              }
        
              return Json(responseData);
          }
        
        
          public ResignationRequester ResignationupdateReason(int RequestNo, string Reason)
          {
              ResignationRequester resignationRequester = new ResignationRequester();
              resignationRequester.Reason = Reason;
              resignationRequester.RequestNo = RequestNo;
              return resignationRequester;
          }
    

    Note: Assuming using ResignationupdateReason method you are writing into database.

    Output:

    enter image description here

    Note: I have just shared the Idea using onblur event, you can try out other event listener from the official document here.

    Login or Signup to reply.
  2. You can set an oninput to the textarea and send data everytime the user types something:

    $('#Reason').children('textarea').on('input', function(){
        let data = $(this).val()
        $.ajax({
            url: /* your route */,
            method: /* your preferred method */,
            data: data,
            success: res => console.log('you got it!')
        })
    })
    

    You might want to abort the older requests if the user’s still typing and only send the latest one too, but let’s settle with this for now.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search