6

I am trying to set up a simple login html page, whose action is sent to mvc controller on another of my sites. I have no problem setting up the page to do the post, and in the mvc controller I have my method that reads the form post. The problem is that I am not seeing my fields from the html form in the form collection.

Is there something special that I need to do to read a form post within a mvc controller method, if so what is that?


The is the form action markup from my page

<form action="http://reconciliation-local.sidw.com/login/launch" method="post">
    User Name <input type="text" id="username"/><br/>
    Password <input type="text" id="password"/>
    <input type="submit" value="launch"/>


</form>

The controller method

    [HttpPost]
    public ActionResult launch(FormCollection fc)
    {
        foreach (string fd in fc)
        {
            ViewData[fd] = fc[fd];
        }
        return View();
    }

When I step through the controller method code, I am not seeing anything in the formcollection parameter.

2
  • Show the code of your form, please. Commented Oct 31, 2013 at 2:15
  • Also show your controller method. Commented Oct 31, 2013 at 2:34

6 Answers 6

9

Post Html To MVC Controller

  1. Create HTML page with form (don't forget to reference a Jquery.js)

    <form id="myform" action="rec/recieveData" method="post">
    
        User Name <input type="text" id="username" name="UserName" /><br />
        Password  <input type="text" id="password" name="Password"/>
                  <input type="submit" id="btn1" value="send" />
    </form>
    
    <script>
        $(document).ready(function () {
    
             //get button by ID
            $('#btn1').submit(function () {
    
                //call a function with parameters
                $.ajax({
                    url: 'rec/recieveData',  //(rec)= Controller's-name 
                                             //(recieveData) = Action's method name
                    type: 'POST',
                    timeout: '12000', (optional 12 seconds)
                    datatype: 'text',
                    data: {
                        //Get the input from Document Object Model
                        //by their ID
                        username: myform.username.value,  
                        password: myform.password.value,
                    }
    
                });
            });
        });
    
    </script>
    

Then in The MVC Controller

                         controller/action
                             |        |

1. Create Controller named rec (rec/recieveData)

  1. Create View named rec.cshtml

Here is the controller:

 public class recController : Controller
    {
        // GET: rec
        string firstname = "";
        string lastname = "";

        List<string> myList = new List<string>();

        public ActionResult recieveData(FormCollection fc)
        {
          //Recieve a posted form's values from  parameter fc
            firstname = fc[0].ToString(); //user
            lastname = fc[1].ToString();  //pass

           //optional: add these values to List
            myList.Add(firstname);
            myList.Add(lastname);

            //Importan:
            //These 2 values will be return with the below view
            //using ViewData[""]object...
            ViewData["Username"] = myList[0];
            ViewData["Password"] = myList[1];

            //let's Invoke view named rec.cshtml
            // Optionaly we will pass myList to the view
            // as object-model parameter, it will still work without it thought
            return View("rec",myList);
        }
    }

Here is the View:

@{
    ViewBag.Title = "rec";
}

<h2>Hello from server</h2>

<div>
    @ViewData["Username"]<br /> <!--will display a username-->
    @ViewData["Password"] <!-- will display a password-->

</div>
Sign up to request clarification or add additional context in comments.

Comments

1

If you posted some code it would be much easier to help you, so please edit your question...

Make sure that your form's action has the correct address, that your method is specifying POST (method="POST") and that the input fields under your form have name attributes specified.

On the server side, try making your only parameter a FormCollection and test that the fields in your form posted through the debugger. Perhaps your model binding isn't correct and the FormCollection will at least show you what got posted, if anything.

These are just common issues I've seen. Your problem could be different, but we need to see what you're working with to be able to tell.

Comments

1

Try something like this:

cQuery _aRec = new cQuery();
    _aRec.Sqlstring = "SELECT * FROM Admins";
    DataSet aDS = _aRec.SelectStatement();
    DataTable aDT = aDS.Tables[0];
    foreach (DataRow aDR in aDT.Rows){
        if (txtAdminUsername.Text == aDR[0].ToString()){
            if (txtAdminPassword.Text == aDR[1].ToString()){
                Session["adminId"] = aDR[0];
                Response.Redirect("Admin.aspx");
                return;
            }
        }
    }

Comments

0

Make sure that your FormCollection object properties for username and password are defined properly.

3 Comments

Figured it out.....and not sure exactly why this matters, but on the form tag I need to use the name attribute for the fieldnames and not the id attribute. MAde that change, and hey presto it came through...go figure. :)
Makes sense. I believe that's how the controller binds to the form field.
You are correct. To get around that, you have to create your own editor template.
0

I had to use the name attribute on the text tag, and that solved my problem, is now working like a charm.

Comments

0

You have to use Ajax to do that.. Whenever you want to "submit" from client side, you should use Ajax to update the server


Step 1 - you redirect your Ajax call to your action, but with your list of parameters in the query-string appended

$.ajax(url: url + "?" + your_query_string_parameter_list_you_want_to_pass)

Step 2 - add optional parameters to your Controller-action with the same names and types you expect to get returned by the client

public ActionResult MyControllerAjaxResponseMethod(type1 para1 = null, 
                                                   type2 para2 = null, 
                                                   type3 para3 = null, ..)

Know that the optional parameters have to be initialized, otherwise the Action itself will always ask for those

Here's where the "magic" happens though --> MVC will automatically convert the query-string parameters into your optional controller-parameters if they match by name

I was also looking for a good answer for this, --> i.e. - one that doesn't use q-s for that usage, but couldn't find one..

Kinda makes sense you can't do it in any other way except by the url though..

Comments

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.