在ASP.NET MVC视图映射个别按钮控制器动作 [英] Mapping individual buttons on ASP.NET MVC View to controller actions

查看:112
本文介绍了在ASP.NET MVC视图映射个别按钮控制器动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我需要的用户能够更新或从数据库中删除数据行。该行显示用我的视图的.aspx文件foreach循环用户。每一行有两个文本框(txtName的,txtDesc),更新按钮,删除按钮。什么我不知道的,是我有多么​​的更新按钮将消息发送到控制器的哪一行来更新?我可以看到这样的一对夫妇的方式:


  1. 把每行它自己的表单标签内,然后点击更新按钮时,会提交值,该行只(也将有与ROWID一个隐藏字段)和控制器类将采取所有岗位值作为参数传递给控制器​​上的更新方法。

  2. 不知何故,有按钮的方式发回只值一个POST到控制器该行照本宣科。

是否有这样做的一种方式?有一件事我关心的是,如果每一行都有通过ASP.NET(txtName1,txtDesc1,txtName2,txtDesc2),那么如何将它们的值被映射到控制器的方法正确的参数?

解决方案

您可以使用多个表单,并设置表单上的动作是这样的:

 <形式方法=邮报行动=/ YourController / YourAction /<%= ROWID%GT;>

所以,你将有 YourController / YourAction / 1 YourController / YourAction / 2 等。

有没有需要不同的文本框,给出不同的名字,只叫他们txtName的,txtDesc等(甚至更好,摆脱那些TXT prefixes的)。由于它们以不同的形式,就不会混淆了。

然后在你的行动做这样的事情。

 公众的ActionResult YourAction(INT ID,用户名字符串,字符串描述)

其中用户名,说明是你的窗体控件使用相同的名称(因此会自动映射)。 id参数将自动映射到你把表单操作数量。

I have an application where I need the user to be able to update or delete rows of data from the database. The rows are displayed to the user using a foreach loop in the .aspx file of my view. Each row will have two text fields (txtName, txtDesc), an update button, and a delete button. What I'm not sure of, is how do I have the update button send the message to the controller for which row to update? I can see a couple way of doing this:

  1. Put each row within it's own form tag, then when the update button is clicked, it will submit the values for that row only (there will also be a hidden field with the rowId) and the controller class would take all the post values as parameters to the Update method on the controller.
  2. Somehow, have the button be scripted in a way to send back only the values for that row with a POST to the controller.

Is there a way of doing this? One thing I am concerned about is if each row has different names for it's controls assigned by ASP.NET (txtName1, txtDesc1, txtName2, txtDesc2), then how will their values get mapped to the correct parameters of the Controller method?

解决方案

You can use multiple forms, and set the action on the form to be like this:

<form method="post" action="/YourController/YourAction/<%=rowId%>">

So you will have YourController/YourAction/1, YourController/YourAction/2 and so on.

There is no need to give different names to the different textboxes, just call them txtName, txtDesc etc (or even better, get rid of those txt prefixes). Since they are in different forms, they won't mix up.

Then on the action you do something like

public ActionResult YourAction(int id, string username, string description)

Where username, description are the same names that you used on the form controls (so they are mapped automatically). The id parameter will be automatically mapped to the number you put on the form action.

这篇关于在ASP.NET MVC视图映射个别按钮控制器动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆