如何将用户输入从视图传递到MVC中的类

时间:2015-11-23 01:10:14

标签: asp.net-mvc

我想这必须是非常基本的,但我的所有搜索结果只显示如何以其他方式传递数据(模型到控制器,控制器查看,然后查看回控制器,但没有从控制器回到模型(类)我试图将搜索参数的用户输入传递给API的查询字符串。在视图中:

<form method="post" action="~/Models/Search">
<input name="artist" placeholder="Enter artist's name" />

@{Search temp = new Search();
if (Request.Form["artist"] != null)                         //this method doesn't work; trying to get user response and pass it back to search class;
{ temp.Artist = Request.Form["artist"].ToLower(); }         //have to  hardcode search parameter at this time
}
<!--<button>Click Me</button>-->

<script>
var weather = Object();
$(document).ready(function () {
    $('button').click(function () {
       // var artist = $("#artist").val();

        $.get("@Url.Action("SearchArtist", "Home")", function (response) {
            console.log(response);
            artistInfo = ko.mapping.fromJS(response); //populate the artist search object
            ko.applyBindings(artistInfo);
   });
});

});

班级:

public class Search
{
    string artist;
    public string Artist { get; set;}
    public Object getArtistInfo()
    {
        string appID = "*************** ";
        artist = "metallica";
        string url = "http://developer.echonest.com/api/v4/artist/search?api_key="+ appID + "&format=json&name=" + artist + "&results=1&bucket=genre&bucket=songs";
        //synchronous client;
        var client = new WebClient();
        var content = client.DownloadString(url);
        var serializer = new JavaScriptSerializer();
        var jsonContent = serializer.Deserialize<Object>(content);
        return jsonContent;
    }
}

控制器:

public ActionResult ArtistInfo()
    {
        return View();
    }
    public JsonResult SearchArtist()
    {
        Search artist = new Search();
        return Json(artist.getArtistInfo(), JsonRequestBehavior.AllowGet);

    }

1 个答案:

答案 0 :(得分:0)

尝试将属性(runat =“server”和id =“chooseyourid”)添加到下面的html表单结果中:

如果您想要访问代码中的值,您只需要编写元素的ID,如下所示:

/ artiste.value; /