asp.net - RAZOR 如何在用户单击组件时触发事件

标签 asp.net razor

我是 RAZOR 新手,我想在用户单击 RadioButton 时触发事件。

理想情况下,它应该在用户单击 RadioButton 后动态显示所选值。

问题:

  1. 如何获取选定的值

  2. 如何在用户单击 RadioButton 时触发事件。

    @{
        Layout = "~/_SiteLayout.cshtml";
        Page.Title = "Contact";
     }
    
    <div>
      <table>
        <tr>
          <td>
             @Html.RadioButton("Gender", "Male", true) Male
          </td>
          <td>
             @Html.RadioButton("Gender", "Female", false) Female
          </td>
        </tr>
     </table>
          @Html.Label(Request["Gender"] == null ? "No Selection" : Request["Gender"])
    

最佳答案

你不能用 Razor 做到这一点,你可以做的是像这样创建单选按钮并使用 Jquery 触发任何操作。

<input type="radio" name="sex" value="male" /> Male <br />
<input type="radio" name="sex" value="female" /> Female

您可以在页面上添加脚本(假设您可以使用 jQuery),例如:

<script type="text/javascript">
$(function () {
    $(':radio[name="sex"]').change(function () {
        $.ajax({
            url: 'sex',
            type: 'POST',
            data: { sex: $('radio[name="sex"]').val() },
            success: function (xhr_data) {
                alert(xhr_data.someValue);
            }
        });
    });
});

假设您在与生成 View 的 Controller 相同的 Controller 中有一个操作方法:

public class YourController : Controller
{
   public ActionResult sex(string sex)
   {
      // do something awesome
      return Json(new { someValue = "testing!" });
   }
}

关于asp.net - RAZOR 如何在用户单击组件时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12420460/

相关文章:

c# - 使用 HtmlAgilityPack 编写 LINQ 来解析 aspx 页面

c# - 如何在 Asp.net 中获取 CheckBoxList 中的选定项

c# - 显示多列复选框列表

c# - Razor 总是显示默认时间而不是数据库字段中的时间

asp.net-mvc-3 - 如何对部分 View 进行批量持久化?

iis - 虚拟目录未配置为 IIS 中的应用程序

c# - 无法通过 smtp 服务器发送邮件,因为出现 'operation timeout' 错误

javascript - bootstrap 数据表 javascript 在 asp.net Repeater 中不起作用

c# - Asp.net MVC 中的部分 View 有什么意义

razor - 智能感知自动完成在错误的位置插入文本