user3329046
user3329046

Reputation: 41

How do i access html input in a razor file, and save it into a c# variable?

I have a .cshtml (Razor) file where i am trying to use System.Web.UI.Page.Request to access information from html input. i am developing in Visual studio 2015.

here is my code:

<!doctype html>
<html ng-app="createEvent">
@using System.Web;
@{   
    string title = Request["title"];
    string address = Request["address"];

    <p>
        You entered: <br />
        Your Title: @title <br />
        Your Address: @address
    </p>

}

With Html input:

<md-input-container class="md-block" flex-gt-xs="">
    <label>Title</label>
    <input type="text" name="title" />
</md-input-container>

<md-input-container class="md-block">
    <label>Address</label>
    <input type="text" name="address">
</md-input-container>

<md-button class="md-raised">
    <input type="submit" value="Submit" />
</md-button>

I have included System.Web in my references for the project, but it does not recognize "Request". Intellisense gives me the message: "The name 'Request' does not exist in the current context".

If i should not be trying to use "Request", how else could i get the input information into c# variables?

Upvotes: 1

Views: 1217

Answers (1)

Tim M.
Tim M.

Reputation: 54417

While you can access the Request object via Context.Request in a view, you should rarely do so, certainly not to access values from form fields in the same view.

You need to wrap your input elements in a form with an action URL of a controller. The controller will receive the data from the form, and you can act on it there.

@using( Html.BeginForm( "Save", "MyController", FormMethod.Post ) )
{
    // your inputs here
}
  1. Define a model that you want to populate.
  2. Create a form for the model.
  3. Submit the form to a controller action method that will automatically turn the HTTP Request into a model that can be read.

Upvotes: 1

Related Questions