c# - 从 URL 获取查询参数到 MVC 视图
问题描述
我有一个href
指向页面的链接,该页面向链接添加了一个参数,例如:
tsw/register-your-interest?Course=979
我要做的是提取Course
ie 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"]});
谢谢大家
解决方案
根据您提供的表单代码,您需要使用@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
}
推荐阅读
- python - 将数据从数据框附加到 JSON
- asynchronous - 使用c ++的Grpc异步双向客户端
- asp.net - 如何在 Asp.net 中隐藏错误请求 400 的响应标头
- python-3.x - 格式化电脑后出现编译问题
- php - 如何在 CodeIgniter 中使用 JWPlayer?
- docusaurus - 使侧边栏不可折叠并始终在 docusaurus V2 经典预设中展开
- python - Visual Studio Code:在没有相应 .py 文件的情况下使用 .pyd 文件时可以使用 Intellisense /“转到定义”吗?(pywin32)
- c# - 如何在 Polly 中创建策略以支持 http 响应 retry-after 标头
- vue.js - vue渲染的问题 Json返回良好但不显示
- java - 如何分别打印给定数字的每个数字?