【问题标题】:url not working in MVC with parametersurl 在带有参数的 MVC 中不起作用
【发布时间】:2018-04-06 03:56:46
【问题描述】:

我正在MVC 开发一个项目,它一直工作正常,但我无法解决错误,我尝试访问从global. asax 创建的带有参数的url,但它给了我错误代码 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>");

我的控制器的 actionresult 也是如此

public ActionResult Unit(int id, string name)
{

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

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

【问题讨论】:

  • 你检查过inspect元素中的url吗?
  • 抱歉,我该怎么做?
  • 其实点击链接后就可以查看网址了。并将其粘贴到问题中

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


【解决方案1】:

在 div 点击事件中应用这个。

 $.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
                }
            });

【讨论】:

  • 这需要直接进入你的剃须刀页面顺便说一句。不在js页面中。如果你想在 js 页面中使用它,你可以在你的 razor 页面中使用var myUrl = "@Url.Action("Action","Controller")"。然后在上面的代码中url = myUrl
  • 我想直接从 razor 执行此操作,div 的 url 中已经有参数,以便 actionresult 接收它们并返回我的数据视图
【解决方案2】:

这是一种更简洁的方法来解决这个问题。你可以像这样使用你的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/")" 可帮助您确保当前页面使用的是准确的 URL。

这里是 jquery 的一个示例用法:https://jsfiddle.net/xpvt214o/61226/

【讨论】:

    猜你喜欢
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2018-10-24
    • 2014-12-13
    • 2016-12-21
    • 1970-01-01
    相关资源
    最近更新 更多