Prady
Prady

Reputation: 11300

Post to an external form from a controller in mvc5

I have a form in a mvc5 view with a button. I need to process this form in the controller and add a few more field values which is picked up from the controller and then posted to an external url.

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Deal</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.First_Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.First_Name, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.First_Name)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Last_Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Last_Name, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Last_Name)
            </div>
        </div>
<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" name="save" /> 
                <input type="submit" value="Register Deal" class="btn btn-default" name="submit" />
            </div>

        </div>

Controller

public ActionResult Create([Bind(Include = "Id,Name,Company,Telephone,Fax,Email,Title,Status,OpportunityAmount,First_Name,Last_Name,City,State,Country,Zip")] Deal deal, String submit)
    {
        if (ModelState.IsValid)
        {
           // do some processing and submit to another external form
        }


    }

Any thoughts on how we can accomplish this ?

One use case would be if an username is provided the user then i would need to query from database the first last name, age etc and submit it to registration form of another site

Upvotes: 2

Views: 1093

Answers (1)

fly_ua
fly_ua

Reputation: 1054

You can post using Web Request Method. E.g.

public void post()
{
    string URL = "http://";
    System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    Stream reqStream = webRequest.GetRequestStream();
    string postData = Request.QueryString; //you form data in get format 
    byte[] postArray = Encoding.ASCII.GetBytes(postData);
    reqStream.Write(postArray, 0, postArray.Length);
    reqStream.Close();
    StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream());
    string Result = sr.ReadToEnd();
}

Upvotes: 3

Related Questions