0

I have seen couple of similar post but none of them resolved my problem, hence I am posting again.

I am trying to pass my WindowsForm data to a asp.net MVC controller.

But at controller I am receiving null value. How can I pass my windows form value (text value) to my controller? Kindly help.

Here are my codes:

Windows form code:

private void send_button_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(textBox1.Text))
        {
            var dataBytes = System.Text.Encoding.UTF8.GetBytes(textBox1.Text);

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:61174/Home/DataFromWinForm");
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.ContentLength = dataBytes.Length;
            httpWebRequest.Method = "POST";

            using (var dataStream = httpWebRequest.GetRequestStream())
            {
                dataStream.Write(dataBytes, 0, dataBytes.Length);
            }


            HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            { starts_label.Text += "Posted";
                textBox1.Text = null;
            }

        }
    }

And here is my controller: by Start method I am opening my windowsform application and trying to pass windows form text to my controller's DataFromWinForm method

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
    public IActionResult Start()
    {
        var appLocation = @"C:\Users\RFIDReader\bin\Debug\RFIDReader.exe";
        Process test = new Process();
        test.StartInfo.FileName = appLocation;
        test.Start();

        return View("Index");
    }
    [HttpPost]
    public IActionResult DataFromWinForm(string receivedData)
    {
        //My code goes here
        return View();
    }}

But when my breakpoint hits at my controller I am getting null value enter image description here

0

1 Answer 1

1

Change this

 var dataBytes = System.Text.Encoding.UTF8.GetBytes(textBox1.Text);

to this

 var postData = HttpUtility.UrlEncode("receivedData") + "=" + HttpUtility.UrlEncode(textBox1.Text);
 var dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You @Gökten Karadağ :) I have modified your code a little. I have used "WebUtility" from "System.Net" Namespace instead of "HttpUtility" Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.