Search code examples
c#asp.netasp.net-corerazorrazor-pages

How to capture the URL input and append it to a text box in razor pages?


I am just starting out in razor pages and I need some help with getting the user's inputted URL on a submit and appending it to a local text file. This is for testing purposes, I know it is not common practice to append to a text file.

Here is my html/razor page

@page
@model UploadModel
@{
    ViewData["Title"] = "Upload a Link";
 }
 <h2>@ViewData["Title"]</h2>
 <h3>@Model.Message</h3>

 <form method="post">
   <div class="textBox">
       <input type="url" data-val="true" data-val-url="The Website field is not a valid fully- 
           qualified http, https, or ftp URL." id="input_URL" name="inputURL" value="" />
    <br />
    <button id="submit" type="submit" value="Submit" onclick="btnSubmit_Click()" 
      class="btn btn-primary" runat="server">Submit</button>
   </div>
 </form>

My C#/backend code

   public class urlClass
{
    [BindProperty]
    public string userInput { get; set; }

    private void OnPost()//btnSubmit_Click(object sender, EventArgs e)
    {
        using (StreamWriter writerURL = new StreamWriter("log.txt"))
        {
            urlClass urlc = new urlClass();
            urlc.userInput = ;
            writerURL.WriteLine(urlc.userInput);
        }
    }
}

}


Solution

  • You can try to change userInput to inputURL.Because .net core bind model with name.And you can change private void OnPost() to public void OnPost().So that it can be triggered.Here is a working demo:

    cshtml:

    <form method="post">
        <div class="textBox">
            <input type="url" data-val="true" data-val-url="The Website field is not a valid fully-
               qualified http, https, or ftp URL." id="input_URL" name="inputURL" value="" />
            <br />
            <button id="submit" type="submit" value="Submit" 
                    class="btn btn-primary" runat="server">
                Submit
            </button>
        </div>
    </form>
    

    cshtml.cs:

    [BindProperty]
            public string inputURL { get; set; }
    
            public void OnPost()//btnSubmit_Click(object sender, EventArgs e)
            {
                using (StreamWriter writerURL = new StreamWriter("log.txt"))
                {
                    //urlClass urlc = new urlClass();
                    //urlc.userInput = ;
                    writerURL.WriteLine(inputURL);
                }
            }
    

    result: enter image description here