点击提交按钮后 URL 更改 如何在不更改的情况下保持原样?

after click on submit button URL change How to keep it as it is without changes?

提问人:ahmed abdelaziz 提问时间:9/11/2023 最后编辑:ahmed abdelaziz 更新时间:9/11/2023 访问量:56

问:

我在 ASP.NET MVC 剃须刀页面上工作。我面临问题 Url 从

Resignation/RequesterIndex?filenumber=103085

Resignation/Create

点击提交按钮后。

我需要像以前一样的 URL,单击提交按钮后没有更改。请问该怎么做?

我的代码上有什么问题导致这个问题?

我的代码详细信息如下

@model HR.WorkforceRequisition.Models.ResignationRequester

@{
    ViewBag.Title = "Requester Index";
}

@using (Html.BeginForm("Create", "Resignation", FormMethod.Post, new { enctype = "multipart/form-data", @id = "ResignationForm", style = "padding-top: 50px" }))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
    @if (!string.IsNullOrEmpty(ViewBag.errorMsg))
    {
        <div class="alert alert-danger">
            @ViewBag.errorMsg
        </div>
    }

    @if (!string.IsNullOrEmpty(ViewBag.successMessage))
    {
        <div class="alert alert-success">
            @ViewBag.successMessage
        </div>
    }

    <div class="row">
        <div class="form-group col-md-6 hover">
            <div class="col-md-5">
                @Html.LabelFor(model => model.Dept, htmlAttributes: new { @class = "control-label" })
            </div>

            <div class="col-md-7">
                @Html.EditorFor(model => model.Dept, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Dept, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group col-md-6 hover">
            <div class="col-md-5">
                @Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "control-label" })
            </div>

            <div class="col-md-7">
                @Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>

    <div class="row">
        <div class="form-group col-md-6 hover">
            <div class="col-md-5">
                @Html.LabelFor(model => model.ResignationSubmissionDate, htmlAttributes: new { @class = "control-label" })
            </div>

            <div class="col-md-7">
                @Html.EditorFor(model => model.ResignationSubmissionDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ResignationSubmissionDate, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group col-md-6 hover">
            <div class="col-md-5">
                @Html.LabelFor(model => model.MobileNo, htmlAttributes: new { @class = "control-label" })
                <span class="text-danger"> *</span>
            </div>

            <div class="col-md-7">
                @Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.MobileNo, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-0 col-md-12">
            <input type="submit" value="Submit" class="btn btn-success" />
        </div>
    </div>
</div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}




  public class ResignationController : Controller
    {

        #region Requester Actions
        // GET: Resignation
        public ActionResult RequesterIndex(string filenumber)
        {
            int maxRequest = 0;
            string userRole = "";
            ResignationRequester resignationRequester = new ResignationRequester();
            int employeeFileNo;
            
            if (!string.IsNullOrEmpty(filenumber))
            {
               
              
                if (int.TryParse(filenumber, out employeeFileNo))
                {
                    JDEUtility jde = new JDEUtility();
                    userRole = Workforce.GetUserRole(employeeFileNo);
             
                    
                    var EmpName = jde.GetEmployeeDetailsForResignation(employeeFileNo);
                    if (EmpName.Count==0)
                    {
                        // ViewBag.errorMsg = "No Data For This File No";
                        return RedirectToAction("UnauthorizedUser", "Home", null);
                    }
                    else
                    {
                        Session[SessionKeys.UserCode] = resignationRequester.EmpID = employeeFileNo;
                        Session[SessionKeys.Username] = resignationRequester.EmpName = EmpName[0];
                        Session[SessionKeys.Department] = resignationRequester.Dept = EmpName[3];
                        Session[SessionKeys.Designation] = resignationRequester.Designation = EmpName[4];
              
                        resignationRequester.EmpID = employeeFileNo;
                        resignationRequester.EmpName = EmpName[0];
                        resignationRequester.MobileNo = EmpName[5];
                        Session[SessionKeys.DepartmentCode] = EmpName[6];
            
                        resignationRequester.ResignationSubmissionDate = DateTime.Now;
                        resignationRequester.Designation = EmpName[4];
                        Session[SessionKeys.NoticePeriod] = Convert.ToInt32(EmpName[2]);
                        resignationRequester.LastWorkingDate = DateTime.Now.AddMonths(Convert.ToInt32(EmpName[2]));
                        Session[SessionKeys.SubmitionDate] = resignationRequester.ResignationSubmissionDate;
                        Session[SessionKeys.LastWorkingDate] = resignationRequester.LastWorkingDate;
                    }
                   
                }
                else
                {
                    ViewBag.errorMsg = "incorrect file no";
                }
            }
            else
            {
                ViewBag.errorMsg = "unauthorized user";
            }
            return View(resignationRequester);
        }
       
       
        
      
        

        [HttpPost]
        public ActionResult RequesterIndex(ResignationRequester resignationRequester)
        {
          
            var filenumber = resignationRequester.EmpID;
            if (Session[SessionKeys.UserCode] != null)
            {
                resignationRequester.DeptCode = Session[SessionKeys.DepartmentCode].ToString();
                resignationRequester.EmpID = Convert.ToInt32(Session[SessionKeys.UserCode]);
                resignationRequester.EmpName = Convert.ToString(Session[SessionKeys.Username]);
                resignationRequester.Dept = Convert.ToString(Session[SessionKeys.Department]);
                resignationRequester.Designation = Convert.ToString(Session[SessionKeys.Designation]);
                int noticeperiod = Convert.ToInt32(Session[SessionKeys.NoticePeriod]);
                int julianRequestDate = 0;// JulianDate.DateTimeToJulian(resignationRequester.LastWorkingDate);
                int SubmitionDate = 0; //JulianDate.DateTimeToJulian((DateTime)Session[SessionKeys.SubmitionDate]);
                JDEUtility jde = new JDEUtility();


                var propertiesWithErrors = ModelState.Where(x => x.Value.Errors.Any())
                                             .Select(x => x.Key)
                                             .ToList();
                //  Workforce.InsertToReignation(resignationRequester, (string)Session[SessionKeys.Username],(DateTime)Session[SessionKeys.LastWorkingDate], noticeperiod, (int)Session[SessionKeys.UserCode]);
                if (ModelState.IsValid)
                {
                    if (resignationRequester.DirectManager == 0)
                    {
                        ViewBag.errorMsg = "Department Manager Must Be Bigger Than 0";
                        goto InvalidModel;
                    }
                    if (Convert.ToString(resignationRequester.LineManager).Length < 6 && !string.IsNullOrEmpty(resignationRequester.LineManager.ToString()))
                    {
                        ViewBag.errorMsg = "Length Line Manager Must Be equal 6 or More";
                        goto InvalidModel;
                    }
                    if (Convert.ToString(resignationRequester.DirectManager).Length < 6 && !string.IsNullOrEmpty(resignationRequester.DirectManager.ToString()))
                    {
                        ViewBag.errorMsg = "Length Direct Manager Must Be equal 6 or More";
                        goto InvalidModel;
                    }
                    if (!string.IsNullOrEmpty(Convert.ToString(resignationRequester.LineManager)) && resignationRequester.LineManagerName == null)
                    {
                        ViewBag.errorMsg = "Line Manager Name Blank";
                        goto InvalidModel;
                    }
                    if (julianRequestDate > 0 && SubmitionDate > 0 && julianRequestDate < SubmitionDate)
                    {
                        ViewBag.errorMsg = "Last Worked Date Must be Bigger than Submit Date";
                        goto InvalidModel;
                    }
                  
                    int checkEmployeeNoExist = jde.CheckEmployeeExistOrNot(resignationRequester.EmpID);
                    if (checkEmployeeNoExist >= 1)
                    {
                        ViewBag.errorMsg = "Employee Exist Before";
                        goto InvalidModel;
                    }

                  
                    try
                    {
                        Workforce.InsertToReignation(resignationRequester, (string)Session[SessionKeys.Username], (DateTime)Session[SessionKeys.LastWorkingDate], noticeperiod, (int)Session[SessionKeys.UserCode]);
                    }
                    catch (Exception ex)
                    {
                        ViewBag.errorMsg = "Create Not Done Correctly";
                    }
                    Session[SessionKeys.DirectManager] = GetEmployeeName(Convert.ToString(resignationRequester.DirectManager));
                    Session[SessionKeys.LineManager] = GetEmployeeName(Convert.ToString(resignationRequester.LineManager));
                    if (string.IsNullOrEmpty(ViewBag.errorMsg))
                    {
                        ViewBag.successMessage = "Resignation Submission form Created successfully";
                    }

                 
                }
                else
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                            .Where(y => y.Count > 0)
                                            .ToList();
                    ViewBag.errorMsg = "Some Required Fields Not Added";
                    goto InvalidModel;
                }
            }
            else
            {
                ViewBag.errorMsg = "No Data For This File No";
            }
        InvalidModel:
            ViewBag.isPostBack = true;
                return View(resignationRequester);
           // return RedirectToAction("RequesterIndex", new { filenumber = resignationRequester.EmpID });
        }
        public async Task<ActionResult> Details(int? id, string msg)
        {

            ViewBag.msg = msg;
            ViewBag.AllowDelete = false;
            ViewBag.AllowApprove = true;
          
   
            ResignationRequester workforceRequest = Workforce.ResignationGetRequestByID((int)id);
            
         

       
          
           
           
          


           

            return View(workforceRequest);
        }


     




        
    }
}

在 requestindexer.cshtml 上

 $("#ResignationApp").submit(function (e) {
                e.preventDefault(); // Prevent the default form submission

                // Serialize the form data
                var formData = $(this).serialize();
                console.log("data is" + formData)
                $.ajax({
                    type: "POST",
                    /* url: "/Resignation/RequesterIndex", // Replace with your actual URL*/
                    url: '@Url.Action("RequesterIndex", "Resignation")',
                   data: formData,
               /*     data: JSON.stringify(formData),*/
         /*           contentType: "application/json",*/

                //            headers: {
                //    RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                //},
                    success: function (response) {
                        // Handle the success response here
                        $("#successMessage").show();
                    },
                    error: function (error) {
                        // Handle any errors here
                        console.error(error);
                    }
                });
            });

模型 ResignationRequester:

public class ResignationRequester
{
    [Required]
    [Display(Name = "Dept./ Branch: ")]
    public string Dept { get; set; }

    [Required]
    [Display(Name = "Designation: ")]
    public string Designation { get; set; }

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

    [Required]
    [Display(Name = "Mobile No: ")]
    public string MobileNo { get; set; }
}

更新的帖子

下面答案的示例代码工作正常,并使 AJAX

对 API 的请求和操作

但验证符号不起作用

那么如何解决这个问题

我将假设辞职是控制者,而行动和视图是

RequesterIndex 并且不需要创建,因为此问题发生在同一个

控制器操作

调查后,我删除了

e.preventDefault();

验证显示

那么如何显示验证,同时不更改URL

jQuery ajax ASP.NET-MVC-4 C#-7.0

评论

0赞 ahmed abdelaziz 9/11/2023
所以我做了什么来解决这个问题,你能通过修改上面的代码给我更多细节吗
0赞 ahmed abdelaziz 9/11/2023
好的,你能和我分享源代码吗,我可以给我你需要的任何细节
0赞 Roe 9/11/2023
应更改为 .这将自动路由到该函数Html.BeginForm("Create",Html.BeginForm("FunctionYouWantToAccess"
0赞 ahmed abdelaziz 9/11/2023
怎么做,你能给我看看吗
0赞 Roe 9/11/2023
您能否编辑您的问题以将函数包含在您尝试发布此请求的函数中?这样我们就可以诊断出实际发生的事情。我假设您的函数是根据您想要的上述路由调用的ResignationControllerRequesterIndex

答:

1赞 Yasin ARLI 9/11/2023 #1

代码指定应将表单发布到“辞职”控制器的“创建”操作。这就是为什么您在提交表单后看到 URL 更改为“辞职/创建”的原因。

您可以使用 AJAX 提交表单,而不会导致页面刷新

<!DOCTYPE html>
<html>
<head>
    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <form id="myForm">
        <!-- Your form fields here -->
        <input type="text" name="Dept" id="Dept">
        <input type="text" name="Designation" id="Designation">
        <!-- Add other form fields as needed -->
        <button type="submit">Submit</button>
    </form>

    <!-- Display success message here -->
    <div id="successMessage" style="display: none;">
        Form submitted successfully!
    </div>

    <script>
        $(document).ready(function () {
            $("#myForm").submit(function (e) {
                e.preventDefault(); // Prevent the default form submission

                // Serialize the form data
                var formData = $(this).serialize();

                $.ajax({
                    type: "POST",
                    url: "/Resignation/Create", // Replace with your actual URL
                    data: formData,
                    success: function (response) {
                        // Handle the success response here
                        $("#successMessage").show();
                    },
                    error: function (error) {
                        // Handle any errors here
                        console.error(error);
                    }
                });
            });
        });
    </script>
</body>
</html>

评论

0赞 ahmed abdelaziz 9/11/2023
所以我做了什么来解决这个问题,你能通过修改上面的代码给我更多细节吗
0赞 Yasin ARLI 9/11/2023
您可以使用 JavaScript 和 AJAX 异步提交表单,而不会导致页面刷新。这样,URL 不会更改,您可以根据需要更新页面内容。Jquery包含在您的项目中?我可以分享一个示例代码。
0赞 ahmed abdelaziz 9/11/2023
好的,你能和我分享源代码吗,我可以给我你需要的任何细节
0赞 ahmed abdelaziz 9/11/2023
查看更新的答案
0赞 ahmed abdelaziz 9/11/2023
调查后,我删除了 e.preventDefault();验证显示,那么如何显示验证,同时不更改URL