【问题标题】:How to pass a variable from View to Controller in ASP .NET如何在 ASP .NET 中将变量从视图传递到控制器
【发布时间】:2015-09-03 05:43:04
【问题描述】:

我发现了与我类似的问题,但在所有这些示例中,变量都是模型的一部分。我正在尝试传递一个在 javascript 中创建的变量,它不是模型的一部分。

代码:

 $(document).ready(function () {

    var url = document.URL;
    var index = url.indexOf("?email=");
    var email;

    /* If there is an EMAIL in URL, check directory to confirm it's valid   */
    if (index > -1) {
        /* There is an email */
        email = url.substr((index + 7));
        email = email.substr(0, (email.length - 4)) + "@@mymail.ca";

        /* Check directory to see if this email exists */
        @Html.Action("CheckDirectory", "Home", new { email = ???});

    }
});

有没有办法填写???使用上面的电子邮件?

【问题讨论】:

  • @Html.Action() 的使用没有任何意义。它会在客户端 JavaScript 中产生语法错误。至于“传递值”,您可以使用 JavaScript 更新客户端标记。因此,如果有东西要发布到控制器,那么您可以在标记中的 URL 上设置它,或者为表单发布设置表单元素的值。或者您可能想向控制器方法发出 AJAX 请求以执行某些操作?真的不清楚你甚至想在这里做什么。
  • 你需要了解AJAX。
  • @David 我在这个视图上有一个 Kendo 调度程序,如果他们有一个有效的帐户,它将允许人们创建预订。要检查帐户目录,我必须导航到外部 URL 以抓取电子邮件列表(帐户 ID)。所以在我加载调度程序之前,我试图在 Home 控制器中调用“CheckDirectory”来验证电子邮件是否有效。
  • @SLaks 我现在正在研究 AJAX,谢谢。
  • 你是想将当前页面重定向到/home/checkdirectory,还是调用一个ajax函数并对结果做些什么?

标签: javascript html asp.net asp.net-mvc


【解决方案1】:

您可以在控制器 URL 中将您的值作为 GET 参数传递:

$(document).ready(function () {

  var url = document.URL;
  var index = url.indexOf("?email=");
  var email;

  /* If there is an EMAIL in URL, check directory to confirm it's valid   */
  if (index > -1) {
    /* There is an email */
    email = url.substr((index + 7));
    email = email.substr(0, (email.length - 4)) + "@@mymail.ca";

    /* Check directory to see if this email exists */
    window.location.href = '/CheckDirectory/Home?email=' + email;
  }
});

【讨论】:

    【解决方案2】:

    回答你的问题

    有没有办法填写???使用上面的电子邮件?

    没有。 Razor 代码类似于 PHP 或任何其他服务器端模板语言——它在发送响应之前在服务器上进行评估。所以,如果你有类似的东西

    @Url.Action("checkdirectory", "home")
    

    在您的脚本中,假设它直接在视图中,它将被生成的 URL 替换,例如

    /home/checkdirectory
    

    您的代码,它使用

    @Html.Action("checkdirectory", "home")
    

    实际上执行一个单独的操作,并将响应作为字符串注入到调用它的视图中。可能不是你想要的。

    所以,让我们试着让你走上正确的道路。假设你的控制器动作看起来像

    [HttpGet]
    public ActionResult CheckDirectory(string email = "")
    {
        bool exists = false;
    
        if(!string.IsNullOrWhiteSpace(email))
        {
            exists = YourCodeToVerifyEmail(email);
        }
    
        return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
    }
    

    你可以,使用 jQuery(因为 XMLHttpRequests 标准化并不有趣),做类似的事情

    $(function(){
    
        var url = '@Url.Action("checkdirectory", "home")';
    
        var data = { email : $('#email').val() };
    
        $.get(url, data)
            .done(function(response, status, jqxhr) {  
    
                if(response.exists === true) {
                    /* your "email exists" action */
                }
                else {
                    /* your "email doesn't exist" action */
                }
    
            })
            .fail(function(jqxhr, status, errorThrown) { 
                /* do something when request errors */
            });
    
    });
    

    这假设您有一个<input /> 元素,其中idemail。相应调整。此外,Url 助手只能在视图中使用;如果您在单独的 JavaScript 文件中执行此操作,请将其替换为硬编码字符串(或其他适合您的字符串)。

    编辑:

    由于我似乎没有完全理解你想要做什么,这里有一个基于用户“类型”返回不同视图的示例:

    public ActionResult ScheduleMe(string email = "")
    {
        if(!string.IsNullOrWhiteSpace(email))
        {
            ActionResult response = null;
            var userType = YourCodeToVerifyEmail(email);
    
            // Assuming userType would be strings like below
            switch(userType)
            {
                case "STAFF":
                    response = View("StaffScheduler");
                    break;
    
                case "STUDENT":
                    response = View("StudentScheduler");
                    break;
    
                default:
                    response = View("ReadOnlyScheduler");
                    break;
            }
    
            return response;
        }
    
        return View("NoEmail");
    }
    

    这假设您将有 4 个可能的视图:您提到的三个,加上没有给出电子邮件参数时的“错误”视图(您也可以通过重定向到另一个操作来处​​理)。此变体还假设用户以某种方式导航到类似 hxxp://yourdomain.tld/home/scheduleme?email=peter@innotech.com

    【讨论】:

    • @UğurDinç 这些解释有意义吗?此外,您还需要阅读why JsonRequestBehavior.AllowGet was required for the action result - MVC 框架在处理 JSON 值时存在一些问题。
    • 新问题是响应在视图加载后 (~5) 秒出现,而视图应该依赖于响应。即如果电子邮件属于 STAFF,则加载 Staff Scheduler(无限制),否则如果电子邮件属于 STUDENT,则加载 Student Scheduler(限制使用),否则,仅加载 View Scheduler(不可编辑)。
    • 是的,这很有意义。再次感谢。
    • @UğurDinç 这听起来像是您可以/应该在服务器上处理的事情。此代码假定您正在执行现有操作,并且想要查看电子邮件。如果您只是想根据传递给操作的参数显示不同的视图,您需要在返回响应之前处理它。电子邮件来自哪里?
    • 基本上,我会在 URL (?email=mymail) 中收到每个访问该应用程序的人的电子邮件地址(编码)。我需要验证此电子邮件是否存在于目录中。这就是“checkDirectory”的用武之地。控制器中的 CheckDirectory 转到 Web 上的某个页面,并检查此人的电子邮件是否正确。然后根据结果和电子邮件类型(员工与学生),我需要加载其中一个调度程序。
    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多