使用查询字符串传递的值创建记录

发布于 2024-12-10 07:21:22 字数 392 浏览 7 评论 0原文

我正在表中创建一条记录,其中包含外键。外键在查询字符串中传递,我已在 ViewBag 中设置该值。我已将其添加到表单中,但它不起作用。 这是来自控制器的代码:

public ActionResult Create(int propertyId)
{
        ViewBag.storagePropertyId = propertyId;
        return View();
} 

这是来自视图的代码。

@Html.HiddenFor(model => model.propertyId, new { value =ViewBag.propertyId })

这是我应该这样做的吗?如果是的话,这个表格有问题吗?

I am creating a record in a table that has foriegn key in it. The foriegn key is getting passed in the query string and I have set the value in the ViewBag. I have added this to the form but it will not work.
Here is the code from the controller:

public ActionResult Create(int propertyId)
{
        ViewBag.storagePropertyId = propertyId;
        return View();
} 

Here is the code from the view.

@Html.HiddenFor(model => model.propertyId, new { value =ViewBag.propertyId })

Is this how I should be doing this? If so, is there a problem with that form

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晨曦慕雪 2024-12-17 07:21:22

为什么不直接在控制器中设置 Model.PropertyID 的值,或者更好的是在视图模型中设置。

ViewModel

public class MyViewModel()
{
   public int PropertyID { get; set; }

   public MyViewModel() { } 

   public MyViewModel(int propertyID)
   {
      this.PropertyID = propertyID;
   }
}

Action Result

public ActionResult Create(int propertyId)
{
   return View(new MyViewModel(propertyId));
}

View

@model MyViewModel

@Html.HiddenFor(m => m.PropertyID)

那么隐藏字段的值将包含属性 ID 的值。

Why not just set the value of the Model.PropertyID in the controller, or better yet in a viewmodel.

ViewModel

public class MyViewModel()
{
   public int PropertyID { get; set; }

   public MyViewModel() { } 

   public MyViewModel(int propertyID)
   {
      this.PropertyID = propertyID;
   }
}

Action Result

public ActionResult Create(int propertyId)
{
   return View(new MyViewModel(propertyId));
}

View

@model MyViewModel

@Html.HiddenFor(m => m.PropertyID)

Then the value of the Hidden field will contain the value of the property ID.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文