url无法使用参数在MVC中工作

时间:2018-04-06 03:56:46

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

我正在MVC开发一个项目并且它一直在工作,但我无法解决错误,我尝试访问从global. asax创建的带参数的网址它给了我错误代码404。

routes.MapRoute(
        "Unit",
        "Home/Unit/{id}/{name}",
        new { controller = "Home", action = "Unit", id = UrlParameter.Optional }
        );

这里我在jquery中创建路由,我将路由添加到带文本的div

 $('#nombreUnidad').append("<a href='Unit/" + param.Unidad.Id + "/" + param.Unidad.NombreUnidad + "'>Nombre: " + param.Unidad.NombreUnidad + "</a>");

来自我的控制器的动作也是如此

public ActionResult Unit(int id, string name)
{

    return View("~/Views/Home/Unit.cshtml");
}

我想通过单击div来获取该视图,是的,在这种情况下视图将具有模型,它类似于配置文件,这就是为什么在jquery中我创建div的文本的路径能够使用我选择的单位数据返回视图

2 个答案:

答案 0 :(得分:0)

在div click事件中应用它。

 $.ajax({
                type: "POST", //Post or Get
                url: '@Url.Action("Action","Controller")',
                data: JSON.stringify({ id:1, name: 'pp' }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                        //code to handle the response
                },
                error: function () {
                    //code to handle error
                }
            });

答案 1 :(得分:0)

这是一种更清洁的方法来解决这个问题。你可以像这样使用你的jquery:

 $('#nombreUnidad').append(function(){
        return $("<a>").attr("href", $(this).attr("data-appUrl") + ...).text("link text");
 });

此代码直接从HTML中的data-appUrl属性获取您的URL。将URL直接传递给razor要容易得多。像这样:

<div id="nombreUnidad" data-appUrl="@Url.Content("~/Home/Unit/")">
  <span>Here is some <b>sample text</b></span>
</div>

代码data-appUrl="@Url.Content("~/Home/Unit/")"可帮助您确保正确的网址用于当前网页。

以下是jquery的示例用法:https://jsfiddle.net/xpvt214o/61226/

相关问题