Iri*_*USA 4 html c# asp.net-mvc asp.net-mvc-4
我正在尝试设置一个简单的登录html页面,其操作被发送到我的另一个网站上的mvc控制器.我没有问题设置页面来做帖子,在mvc控制器中我有我的方法来读取表单帖子.问题是我没有在表单集合中看到html表单中的字段.
在mvc控制器方法中读取表单帖需要做些什么特别的事情,如果是这样的话是什么?
这是我页面中的表单操作标记
<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>
Run Code Online (Sandbox Code Playgroud)
控制器方法
[HttpPost]
public ActionResult launch(FormCollection fc)
{
foreach (string fd in fc)
{
ViewData[fd] = fc[fd];
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
当我单步执行控制器方法代码时,我在formcollection参数中没有看到任何内容.
小智 7
使用表单创建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>
Run Code Online (Sandbox Code Playgroud)
controller/action
| |
Run Code Online (Sandbox Code Playgroud)
1.创建名为rec的rec(rec/recieveData)
这是控制器:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是视图:
@{
ViewBag.Title = "rec";
}
<h2>Hello from server</h2>
<div>
@ViewData["Username"]<br /> <!--will display a username-->
@ViewData["Password"] <!-- will display a password-->
</div>
Run Code Online (Sandbox Code Playgroud)
如果您发布了一些代码,那么帮助您会更容易,所以请编辑您的问题......
确保表单的操作具有正确的地址,您的方法指定了 POST (method="POST"),并且表单下的输入字段指定了名称属性。
在服务器端,尝试将唯一参数设置为 FormCollection,并测试表单中的字段是否通过调试器发布。也许您的模型绑定不正确,FormCollection 至少会向您显示发布的内容(如果有)。
这些只是我见过的常见问题。您的问题可能有所不同,但我们需要了解您正在处理的问题才能判断。
| 归档时间: |
|
| 查看次数: |
21074 次 |
| 最近记录: |