Home > Mobile >  How Can I Get Action Name of Current View while submitting a form?
How Can I Get Action Name of Current View while submitting a form?

Time:09-17

I have an action method for uploading Image that is used in many Views. after uploading the image I want my method to redirect to the same view. for that I need action name to redirect it and when I try to get the action name by:

var routeValues = HttpContext.Request.RequestContext.RouteData.Values;

if (routeValues != null)
{
   if (routeValues.ContainsKey("action"))
   {
       var actionName = routeValues["action"].ToString();
   }
}

It gives current posted action name i.e.:

public ActionResult UploadImage(HttpPostedFileBase imageUpload, 
    PatientHomeViewModel model)

This is the form in the view while submitting:

@using (Html.BeginForm("UploadImage", "Patient", FormMethod.Post, 
    new { enctype = "multipart/form-data" }))

This form is used in many different views and I need those view's action name for redirecting. whatever I've tried, I only got the current action name.

CodePudding user response:

You can always use jquery ajax or javascript fetch to send the form to the controller, in the action you don't return any view, with the added advantage that the view will not be reoaded, here is a good example:

https://www.aspsnippets.com/Articles/ASPNet-Core-Submit-Form-using-jQuery.aspx

Controller:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult Index(string firstName, string lastName)
    {
        string name = string.Format("Name: {0} {1}", firstName, lastName); ;
        return Json(new { Status = "success", Name = name });
    }
}

Form:

<form id="myForm" method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
    <table>
        <tr>
            <td>First Name: </td>
            <td><input type="text" id="txtFirstName"/></td>
        </tr>
        <tr>
            <td>Last Name: </td>
            <td><input type="text" id="txtLastName"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" value="Submit" onclick="AjaxFormSubmit()"/></td>
        </tr>
    </table>
    <hr/>
    <span id="lblName"></span>
</form>

Script:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    function AjaxFormSubmit() {
        //Set the URL.
        var url = $("#myForm").attr("action");
 
        //Add the Field values to FormData object.
        var formData = new FormData();
        formData.append("firstName", $("#txtFirstName").val());
        formData.append("lastName", $("#txtLastName").val());
 
        $.ajax({
            type: 'POST',
            url: url,
            data: formData,
            processData: false,
            contentType: false
        }).done(function (response) {
            if (response.Status === "success") {
                $("#lblName").html(response.Name);
            }
        });
    }
</script>

Note that the example returns JsonResult but you can still have IActionResult return type and return Ok(), BadRequest(), etc., you can also have an object with properties as a parameter of the controller so long as the property names match the jquery Formdata names, the mapping is automatic.

There are alternatives to this, you can take a look here How to get view name in controller while navigating from view to controller in MVC3 or here Retrieve the current view name in ASP.NET MVC?, you could also compose ViewData or TempData with the hardcoded view name in the view, and access it in the controller, although I still think using javascript is the better option since you already have the view loaded.

If you're going to redirect to another action the javascript looses it's purpose, whitch is you not having to reload the view, so I'd recommend one of the other options.

  • Related