2

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Salman Abbas
  • 174
  • 1
  • 2
  • 14
  • You can use jquery ajax or javascript fetch to send the info, in the action don't return any view, with the added advantage that the view will not be reoaded. – anastaciu Sep 16 '22 at 08:16
  • @anastaciu so there is no way i can do it without using javascript. i wanted to do it using asp.net mvc like routeValues – Salman Abbas Sep 16 '22 at 08:23
  • Yes there are always other ways, of course, take a look here https://stackoverflow.com/q/25430617/6865932 or here https://stackoverflow.com/questions/1268763/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, I just think using javascript is the better option since you already the view loaded. – anastaciu Sep 16 '22 at 08:32
  • Here is a good example https://www.aspsnippets.com/Articles/ASPNet-Core-Submit-Form-using-jQuery.aspx – anastaciu Sep 16 '22 at 08:44
  • thanks for the links i'll try the javascript way. – Salman Abbas Sep 16 '22 at 08:47
  • You're welcome. 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 so long as the property names match the jquery formdata names, the mapping is automatic. – anastaciu Sep 16 '22 at 08:54
  • first, i did it using https://stackoverflow.com/q/25430617/6865932 link. also i am not returning a view, instead i am redirecting to action, for that can i use this link's method or use javascript way? – Salman Abbas Sep 16 '22 at 09:04
  • 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 the link method. – anastaciu Sep 16 '22 at 09:11
  • thanks for helping out. if you want you can post it an answer and ill accept it. – Salman Abbas Sep 16 '22 at 09:13
  • Glad to help and to see you found a solution to your problem. – anastaciu Sep 16 '22 at 11:26

1 Answers1

2

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53