【问题标题】:need to call controller method which return String value from view需要调用从视图返回字符串值的控制器方法
【发布时间】:2014-10-25 15:00:55
【问题描述】:

我想调用一个控制器方法,它从视图中返回一个字符串值,例如假设我有一个控制器方法public string Username(string email)。我想在视图中调用此方法,以便我可以将返回值(即用户名)分配给我的标签。

所以我有两个问题:-

  1. 如何在视图“公共字符串用户名(字符串电子邮件)”中调用此参数化控制器函数。
  2. 并得到它的返回值。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    如果你想显示它:

    @{Html.RenderAction("Username", "ControllerName" , new {email="your email"});} 
    

    如果你想通过 ajax 调用它,使用 '@Url.Action("Username", "ControllerName" , new {email="your email"})' 作为 ajax 请求中的 url

    【讨论】:

    • 你是英雄 :) 谢谢@AlexArt。
    【解决方案2】:

    查看侧面

    @model String
    <label>Model</label>
    

    控制器端

    public ActionResult ReturnString()
    {
    var user=userName//Get user name
    return View(user)
    }
    

    【讨论】:

      【解决方案3】:

      看看 AJAX。如果您使用的是 JQuery,则可以使用 ajax 函数完成此任务。在您的情况下,javascript 看起来像这样:

          $.ajax({
              url: '@Url.Action("Username")',
              data:  { email: "some@email.com" },
              success: function (result) {
                      $('#YourLabel').val(result);
              }
          });
      

      【讨论】:

        【解决方案4】:

        使用下面的代码,同时在控制器动作方法上方添加[HttpPost]属性

         $.ajax({
         // method: 'POST', <-- remove this
         type: 'POST', // <-- add this
         url: '@Url.Action("ActionName","ControllerName")',
         dataType: 'json',
         data: { id: 'Parameter' },
         success: function (data, textStatus, jqXHR) {
            //the data here is returned from your controller action method
         console.log("success");
         },
         error: function () {
             alert('error');
         }
         });
        

        【讨论】:

        • Abhishek,如果它有帮助,你可以投票给答案.. :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-12
        • 2017-01-24
        • 1970-01-01
        • 2014-08-17
        • 2017-01-14
        • 1970-01-01
        相关资源
        最近更新 更多