简体   繁体   中英

Javascript from view routing to the wrong action in the controller

Project environment: C#, MVC 5.0

HTML code from Edit.cshtml :

@Html.EditorFor(model => model.ActiveClient.ClientName, new { 
    htmlAttributes = new { @onchange = "OnNameEdit(this.value)", 
    @class = "form-control" } })

jQuery / JavaScript from Edit.cshtml:

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
<script>
function OnNameEdit(val) {
    window.location.href = "OnNameEdit?Value=" + val;
};
</script>

Code for Action in Controller:

[HttpGet]
public ActionResult OnNameEdit(String Value)
{
    WFViewModel = (WorkflowVM)TempData["WFViewModel"];
    if (Value != null)
    {
        WFViewModel.ActiveClient.ClientName = Value;
    }
    TempData["WFViewModel"] = WFViewModel;
    return RedirectToAction("Edit", "Clients");
}

Action that control goes to instead in the same controller:

// GET: Clients/Edit/5
public ActionResult Edit(int? id)
{
    WFViewModel = (WorkflowVM)TempData.Peek("WFViewModel");
 // Remaining code removed for brevity

The view loads fine. One gets to the field to modify the contents of the ClientName and modifies the contents. When one tabs out of the ClientName control, control flows to the OnNameEdit() function in the scripts portion of the Edit.cshtml file. When that function completes, control transfers to the action named Edit() instead of the Action named OnNameEdit() in the same Controller.

This code is basically identical to the code for the Create view for the same controller, and it works perfectly

Any suggestions would be appreciated.

you can use an AJAX call, like:

function  OnNameEdit(val)
{
   $.ajax({
      url: 'OnNameEdit',
      data: { Value: val }
   }).done(function() {
      alert('OnNameEdit called'); 
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM