日期:2014-05-17  浏览次数:20536 次

如何通过 jq ajax 向 mvc 传递参数?
Controllor
------------------------
C# code

public ActionResult GetResult(string name)
{
    return Content("hello, " + name);
}



View
------------------------
JScript code

<script type="text/javascript">
    function GetMessage() {
        $.get("/Home/GetResult/", function (response) {
            $("#mySpan").html(response);
        });
    }
</script>

<input type="text" maxlength="8" id="characterName" />
<input type="button" onclick="GetMessage()" value="开始" />
<span id="mySpan"></span>



如上,请问如何把 characterName 传递到controllor?

------解决方案--------------------
JScript code

<script type="text/javascript">
    function GetMessage() {
        $.get("/Home/GetResult/"+$("#characterName"), function (response) {
            $("#mySpan").html(response);
        });
    }
</script>

routes.MapRoute(
                "GetMessage", // 流程附件上传
                "{Home}/{GetResult}/{name}", // 带有参数的 URL
                new { controller = "Home", action = "GetResult", name= UrlParameter.Optional} 
            );

public ActionResult GetResult(string name)
{
    return Content("hello, " + name);
}
这样需要在路由中重新配置规则,因为默认路由传递参数为id.



<script type="text/javascript">
    function GetMessage() {
        $.get("/Home/GetResult/?characterName="+$("#characterName"), function (response) {
            $("#mySpan").html(response);
        });
    }
</script>

public ActionResult GetResult()
{
    return Content("hello, " + Request.QueryString["characterName"]);
}