I work on an ASP.NET MVC razor page. I face issue Url change from
我在一个ASP.NET MVC剃刀页面上工作。我面临URL更改的问题
Resignation/RequesterIndex?filenumber=103085
to
至
Resignation/Create
after click submit button.
点击提交按钮后。
I need URL as it was before, without change after click submit button. How to do that please?
我需要像以前一样的URL,点击提交按钮后没有变化。请问怎么做?
What is issue on my code that make this issue?
我的代码中有什么问题导致了这个问题?
My code details as below
我的代码详细信息如下
@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);
}
}
}
on requestindexer.cshtml
在请求indexer.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);
}
});
});
Model 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; }
}
Updated post
更新后的帖子
sample code on answer below is working correctly and make ajax
以下答案上的示例代码工作正常,并使AJAX
request to api and action
接口请求和动作
but validation notation not working
但验证符号不起作用
so How to solve this issue
那么如何解决这个问题呢?
I will assume that Resignation is controller and action and view is for
我将假设辞职是控制者,行动和观点是支持的
RequesterIndex and no need create because this issue happen on same
Requester Index,无需创建,因为此问题发生在同一个
controller action
控制器操作
after investigate I remove
调查后我删除
e.preventDefault();
validation display
验证显示
so how to display validation and on same time not change URL
那么如何在不更改URL的同时显示验证
更多回答
so what I do to solve this issue can you give me more details by modify code above
那么我是怎么解决这个问题的呢?你能通过修改上面的代码给我更多的细节吗
ok good can you please share with me source code i can give me any details you need
好的,你能和我分享源代码吗?我可以提供你需要的任何细节
You should change Html.BeginForm("Create",
to Html.BeginForm("FunctionYouWantToAccess"
. This will auto route to that function
应将Html.BeginForm(“Create”,更改为Html.BeginForm(“FunctionYouWantToAccess”。这将自动路由到该函数
how to do that can you show me please
你能告诉我怎么做吗?
Can you edit you question to include the function inside the ResignationController
you are trying to Post this request to? That way we can diagnose what is actually happening. I assume your function is called RequesterIndex
based on the afore mentioned Route you want
您是否可以编辑您的问题,使其包含您尝试将此请求发布到的ResignationControler中的函数?这样我们就可以诊断出实际发生了什么。我假设您的函数名为Requester Index,基于前面提到的您想要的路径
Your code specifies that the form should be posted to the "Create" action of the "Resignation" controller. That's why you see the URL change to "Resignation/Create" after submitting the form.
您的代码指定表单应该发布到“辞职”控制器的“Create”操作。这就是为什么在提交表单后,您会看到URL更改为“REFICATION/CREATE”。
You can use AJAX to submit a form without causing a page refresh
您可以使用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>
更多回答
so what I do to solve this issue can you give me more details by modify code above
那么我是怎么解决这个问题的呢?你能通过修改上面的代码给我更多的细节吗
You can use JavaScript and AJAX to submit the form asynchronously without causing a page refresh. This way, the URL will not change, and you can update the page content as needed. Jquery included in your project? I can share an example code.
您可以使用JavaScript和AJAX来异步提交表单,而不会导致页面刷新。这样,URL不会更改,您可以根据需要更新页面内容。您的项目中包含jQuery吗?我可以分享一个示例代码。
ok good can you please share with me source code i can give me any details you need
好的,你能和我分享源代码吗?我可以提供你需要的任何细节
check updated answer
检查更新的答案
after investigate I remove e.preventDefault(); validation display so how to display validation and on same time not change URL
在调查之后,我删除了e.PrevenentDefault();验证显示了如何在不更改URL的同时显示验证
我是一名优秀的程序员,十分优秀!