how to update table employee based on request no and when change value of last working date ?

Ahmed Salah Abed Elaziz 390 Reputation points
2023-11-05T00:37:51.78+00:00

I work on asp.net MVC . I face issue I can't change last working date based on RequestNo . without using button submit

meaning when last working date changed then call Edit action inside resignation controller without using submit button when value of input type text last working date changed

I need to using ajax jQuery to do that

Web API I will call it using jQuery ajax is Resignation/Edit

Resignation is controller and edit is action and I will pass object to Edit action result .

I need to do that without using form and I will depend on java script or jQuery

my code as below :

public class ResignationRequester
{


    [Display(Name = "Request No")]
    public int RequestNo { get; set; }


    [Required]
    [Display(Name = "Last Working Day: ")]
    [DataType(DataType.Date, ErrorMessage = "Date only")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime LastWorkingDate { get; set; }
}



[HttpPost]
  [ValidateAntiForgeryToken]
  public async Task<ActionResult> Edit(ResignationRequester req)
  {
//UPDATE last working date based on Request No }

@model HR.WorkforceRequisition.Models.ResignationRequester

@{
    ViewBag.Title = "Details";
    Layout = "~/Views/Shared/_LayoutResignation.cshtml";
}








    <table style="border: 1px solid black;width:100%;">

        <tr>
            <td class="hover" 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>

        </tr>




       
         <tr>
     
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,299 questions
{count} votes

2 answers

Sort by: Most helpful
  1. SurferOnWww 1,996 Reputation points
    2023-11-05T02:28:20.9333333+00:00

    I need to do that without using form and I will depend on java script or jQuery

    I recommend that you use the form tag so that the CSRF token in the hidden field can be sent to the server together with the data of ResignationRequester class. You will be able to do so using the jQuery.

    See the following sample of view including the jQuery ajax:

    @model Mvc5App2.Controllers.ResignationRequester
    
    @{
        ViewBag.Title = "Edit";
    }
    
    <h2>Edit</h2>
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>ResignationRequester</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.RequestNo, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.RequestNo, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.RequestNo, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.LastWorkingDate, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.LastWorkingDate, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.LastWorkingDate, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="button" value="Save" id="ajaxUpdate" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    <div id="result"></div>
    
    @section Scripts {
        <script type="text/javascript">
            //<![CDATA[
            $(function () {
                $('#ajaxUpdate').on('click', function (e) {
                    // use FormData object
                    var fd = new FormData(document.querySelector("form"));
                    $.ajax({
                        url: '/Resignation/Edit',
                        method: 'post',
                        data: fd,
                        processData: false,
                        contentType: false
                    }).done(function (response) {
                        $("#result").empty;
                        $("#result").text(response);
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        $("#result").empty;
                        $("#result").text('textStatus: ' + textStatus +
                            ', errorThrown: ' + errorThrown);
                    });
                });
            });
                //]]>
        </script>
    }
    

  2. Lan Huang-MSFT 26,121 Reputation points Microsoft Vendor
    2023-11-06T05:48:48.4033333+00:00

    Hi @Ahmed Salah Abed Elaziz,

    i don't need to using button to submit exactly i need after change input text text for last working date update data by action resignation/controller edit calling and update data based on request no

    You can use the change event. From my understanding I think the following code can achieve your needs:

    @Html.AntiForgeryToken()
    <div>
        <table style="border: 1px solid black;width:100%;">
    
            <tr>
                <td class="hover" 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>
    
            </tr>
            <tr>
                <td class="hover" style="width: 50%; font-weight: bold; padding-top: 10px;">
                    <div class="form-group hover">
                        @Html.LabelFor(model => model.LastWorkingDate, htmlAttributes: new { @class = "control-label col-md-5" })
                        <div class="col-md-7">
    
                            @Html.EditorFor(model => model.LastWorkingDate, new { htmlAttributes = new { @class = "form-control" } })
                        </div>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
        $('#LastWorkingDate').change(function () {
            var req = {};
            req.RequestNo = $("#RequestNo").text().trim();
            req.LastWorkingDate = $("#LastWorkingDate").val();
            var token = $('input[name="__RequestVerificationToken"]').val();
           
            $.ajax({
                url: '/Resignation/Edit',
                type: 'POST',
                data: {
                    __RequestVerificationToken: token,
                    req: req,
                },
                dataType: 'JSON',
                contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                success: function (response) {      
                        alert('Succesfully!')
                    
                },
                failure: function (response) {
                    alert(response.responseText);
                },  
            })
        });
    </script>
    
    
     [HttpPost]
     [ValidateAntiForgeryToken]
     public async Task<ActionResult> Edit(ResignationRe req)
     {
         if (req != null)
         {
             ResignationRe updatedResignation = (from c in db.ResignationRe
                                                 where c.RequestNo == req.RequestNo
                                                 select c).FirstOrDefault();
             updatedResignation.LastWorkingDate = req.LastWorkingDate;
    
             db.SaveChanges();
         }
    
         return Json(req, JsonRequestBehavior.AllowGet);
     }
    

    Best regards,

    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.