简体   繁体   English

html表单发布到mvc控制器

[英]html form posting to mvc controller

I am trying to set up a simple login html page, whose action is sent to mvc controller on another of my sites. 我正在尝试设置一个简单的登录html页面,其操作被发送到我的另一个网站上的mvc控制器。 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. 我没有问题设置页面来做帖子,在mvc控制器中我有我的方法来读取表单帖子。 The problem is that I am not seeing my fields from the html form in the form collection. 问题是我没有在表单集合中看到html表单中的字段。

Is there something special that I need to do to read a form post within a mvc controller method, if so what is that? 在mvc控制器方法中读取表单帖需要做些什么特别的事情,如果是这样的话是什么?


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. 当我单步执行控制器方法代码时,我在formcollection参数中没有看到任何内容。

Post Html To MVC Controller 将Html发布到MVC控制器

  1. Create HTML page with form (don't forget to reference a Jquery.js) 使用表单创建HTML页面(不要忘记引用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 然后在MVC控制器中

                         controller/action
                             |        |

1. Create Controller named rec (rec/recieveData) 1.创建名为rec的rec(rec / recieveData)

  1. Create View named rec.cshtml 创建名为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>

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. 确保表单的操作具有正确的地址,您的方法指定POST(method =“POST”)并且表单下的输入字段具有指定的名称属性。

On the server side, try making your only parameter a FormCollection and test that the fields in your form posted through the debugger. 在服务器端,尝试将您的唯一参数设置为FormCollection,并测试表单中的字段是通过调试器发布的。 Perhaps your model binding isn't correct and the FormCollection will at least show you what got posted, if anything. 也许你的模型绑定不正确,FormCollection至少会告诉你发布了什么,如果有的话。

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. 您的问题可能会有所不同,但我们需要了解您正在使用的内容才能分辨出来。

确保正确定义了用户名和密码的FormCollection对象属性。

我不得不在文本标签上使用name属性,这解决了我的问题,现在就像魅力一样。

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;
            }
        }
    }

You have to use Ajax to do that.. Whenever you want to "submit" from client side, you should use Ajax to update the server 你必须使用Ajax来做到这一点。每当你想从客户端“提交”时,你应该使用Ajax来更新服务器


Step 1 - you redirect your Ajax call to your action, but with your list of parameters in the query-string appended 第1步 - 您将Ajax调用重定向到您的操作,但附加了查询字符串中的参数列表

$.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 第2步 - 向Controller-action添加可选参数,其中包含您希望客户端返回的相同名称和类型

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 知道必须初始化可选参数,否则Action本身将始终要求这些参数

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 这里是“魔术”发生的地方 - > MVC会自动将查询字符串参数转换为可选的控制器参数(如果它们按名称匹配)

I was also looking for a good answer for this, --> ie - one that doesn't use qs for that usage, but couldn't find one.. 我也在寻找一个很好的答案, - > ie - 一个不使用qs用于那个用法,但找不到一个..

Kinda makes sense you can't do it in any other way except by the url though.. 有点有道理你不能以任何其他方式做到,除了网址虽然..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM