首页 > 解决方案 > 从 URL 获取查询参数到 MVC 视图

问题描述

我有一个href指向页面的链接,该页面向链接添加了一个参数,例如: tsw/register-your-interest?Course=979

我要做的是提取Courseie 979 中的值并将其显示在view. 尝试使用以下代码时,我只返回 0 而不是预期的课程值。理想情况下,我想避免使用routes.

这是视图:

<div class="contact" data-component="components/checkout">

            @using (Html.BeginUmbracoForm<CourseEnquiryPageSurfaceController>("PostCourseEnquiryForm", FormMethod.Post, new { id = "checkout__form" }))
            {
                //@Html.ValidationSummary(false)
                @Model.Course;
            }

我的控制器:

 public ActionResult CourseEnquiry(string Course)
    {
        var model = Mapper.Map<CourseEnquiryVM>(CurrentContent);

        model.Course = Request.QueryString["Course"];
        return model
     }

这是视图模型:

public class CourseEnquiryVM : PageContentVM
{

    public List<OfficeLocation> OfficeLocations { get; set; }
    public string Test { get; set; }
    public string Course { get; set; }
    public List<Source> SourceTypes { get; set; }
}

解决方案:经过一些研究和评论后,我将代码调整为以下,现在可以按预期检索值

@Html.HiddenFor(m => m.Course, new { Value = @HttpContext.Current.Request.QueryString["Course"]});

谢谢大家

标签: c#asp.net-mvcumbraco

解决方案


根据您提供的表单代码,您需要使用@Html.HiddenFor(m => m.Course)而不仅仅是@Model.Course. @Model.Course只是将值显示为文本,而不是构建将发送回控制器的输入元素。

如果您的问题出在您上面引用的视图之前的链接上,这就是我期望的工作:

通过链接查看:

@model CourseEnquiryVM

@Html.ActionLink("MyLink","CourseEnquiry","CourseController", new {course = @Model.Course}, null)

课程控制器:

public ActionResult CourseEnquiry(string course)
{
    // course should have a value at this point
}

推荐阅读