0

I have the following code in my View Jquery portion:

$('#btnContinue').click(function () {                  

     var createFormName = $("#createFormName");
     createFormName.submit();
}

I like to send a temp data from the view to the controller as I need to redirect the user inside the controller's action result based on the temp data value. Is there a way to send temp data from the view to the controller's action result?

Nate Pet
  • 44,246
  • 124
  • 269
  • 414
  • 1
    I can't really see a justification for doing this bc I would think you would just want to add a hidden form field with the value and send it off with the form post submission but you could go old school and set a cookie in js and retrieve it from the controller's method within the http context. That's how temp data is coming from server to client on the backend anyway. – Travis Acton Aug 12 '19 at 19:55

1 Answers1

0

Let's Offer 2 approaches shown with easy examples:

The quickest way is to send it through query String. like this:

    public ActionResult Index()
    {
        TempData["message"] = "Hi";

        return View();
    }

    [HttpGet]
    public ActionResult About(string str1, string str2) { . . . }

then, in your index view:

@{
     string str = TempData["message"].ToString();                            
     @Html.ActionLink("Go to About View", "About", new  { str1 =  @str, str2="some text"})
}

On the other hand, you can Post you data to controller, rather than sending via query string; Let's imagine we have a simple view model here:

public class DoubleStr_ViewModel
{
    public string  str1 { get; set; }
    public string  str2 { get; set; }
}

then inside the controller:

    public ActionResult About()
    {
        TempData["message"] = "Hi";            
        return View(new DoubliStr_ViewModel());
    }

    [HttpPost]
    public ActionResult About(DoubleStr_ViewModel input)
    {
        return View();
    }

And now, inside the About View:

@using Your.Path.To.ViewModels
@model  DoubleStr_ViewModel

<input type="hidden" value="@TempData["message"].ToString()" id="tmpHidden" />

<form method="post">
    @Html.HiddenFor(x => x.str1)
    @Html.TextBoxFor(x => x.str2)
    <button type="submit">SUBMIT</button>
</form>



@section scripts{
    <script>

        $('form').submit(function () {

            $('input#str1').val($('input#tmpHidden').val());
        });
    </script>
    }

In your case, to trigger form submit, you'll have:

$('#btnContinue').click(function () {                  

     // first, fill the hidden value(s) into your model
     $('input#str1').val($('input#tmpHidden').val());

     var createFormName = $("#createFormName");          
     createFormName.submit();
}

Hope, this helps.

A. Nadjar
  • 2,440
  • 2
  • 19
  • 20