使用动作链接将文本框的值从视图传递到控制器 [英] pass value of a textbox from view to controller using actionlink

查看:107
本文介绍了使用动作链接将文本框的值从视图传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的表单中,我有一个如下所示的文本框

In my form I have a textbox as below

@Html.TextBox("first_name")

我需要通过操作链接将此文本框的值传递给控制器​​.

I need to pass the value of this textbox to controller through a actionlink.

我尝试了以下

@Html.ActionLink("View", "view_Details", new { name = first_name})

但这给出了错误

名字"在当前上下文中不存在

"first_name" does not exist in the current context

是否可以使用Actionlink?

Is this possible using a Actionlink?

我的控制器签名是

public ActionResult view_Details(string name)
     {
            return View();
     }

已编辑

 @Html.ActionLink("View", "view_Details", new { name = getname()})

 <script type="text/javascript">
      function getname() {
           return $("#first_name").val();
       }
</script>

我尝试了上面的代码.它也给错误

I tried above code. Its also giving error

getname()在当前上下文中不存在

getname() does not exist in the current context

推荐答案

您需要javascript/jquery来获取文本框的值,然后更新要重定向到的URL

You need javascript/jquery to get the value of the textbox and then update the url you want to redirect to

HTML

@Html.ActionLink("View", "view_Details", new { id = "myLink" }) // add id attribute

脚本

$('#myLink').click(function() {
  var firstname = $('#first_name').val(); // get the textbox value
  var url = $(this).attr('href') + '?name=' + firstname; // build new url
  location.href = url; // redirect
  return false; // cancel default redirect
});

旁注:进一步编辑后,收到该错误的原因是剃刀代码(@Html.ActionLink()在发送到视图之前已在服务器上解析,但是getname()是不存在的客户端方法在那时-即在当前上下文中不存在

Side note: further to you edit, the reason you receive that error is that razor code (the @Html.ActionLink() is parsed on the server before its sent to the view but getname() is a client side method which does not exist at that point - i.e it does not exist in the current context

这篇关于使用动作链接将文本框的值从视图传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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