Search code examples
asp.net-mvcsessionmodel-view-controllertempdata

Passing form values from one controller view to another form on a different controllers view in asp MVC


Okay I'm new to MVC and trying to make me a webpage where I can transfer to small form box with a zip code and button, to quote page that will fill in the zip code part on the quote page.

My problem is I have two controllers a homeController that has a index view with a small form box. I need to pass the zip code to the QuoteController which has it's own view that populated with the new zip code.

the home controller input, indexview

 @using (Html.BeginForm("Quote", "Quote"))    
  <p>Move From Zip:</p>  
 <input type="text" name="Zip"/><br /> 
 <input type="submit" value="Next" name="next">

the quote form to receive the zip, on the quote controller, on the quote view

@Html.Label("Move From Zip ")<br />
@Html.TextBoxFor(m => m.MoveFromZip, "", new { maxlength = 5, @class =    "short-textbox" })

what's the easiest way of doing this


Solution

  • In your Index view of HomeController, you can keep the form action to "Quote/Quote"

    @using (Html.BeginForm("Quote", "Quote"))
    {
      <input type="text" name="Zip" />
      <input type="submit" />
    }
    

    Create a view model for your Quote action method view in QuoteController

    public class QuoteVm
    {
      public string Zip { set;get;
    }
    

    and in your QuoteController's Quote action method

    [HttpPost]
    public ActionResult Quote(QuoteVm model)
    {
      return View(model);
    }
    

    and your Quote view will be

    @model QuoteVm
    <p>Data passed(POSTED) from Index view</p>
    @using(Html.BeginForm("QuoteSave","Quote"))
    {  
      @Html.TextBoxFor(s=>s.Zip)
      <input type="submit" />
    }
    

    Now for your form submit in this view, you need to have another HttpPost action method

    [HttpPost]
    public ActionResult QuoteSave(QuoteVm model)
    {
       // to do : Do something and return something
    }