【问题标题】:Passing value from view to controller将值从视图传递到控制器
【发布时间】:2014-04-20 07:03:31
【问题描述】:

好的,我最近问了一个非常相似的问题,我得到了很好的答案。但是,我可能没有准确地表达我的问题,所以我会在这里再试一次:

这是我的看法

@using (Html.BeginForm())
{
<h3  class="editable">@Model.Title</h3>

<input type="submit" value="submit">   

} 

&lt;h3&gt; 具有 "editable" 类,在这种情况下意味着它可以由内联编辑器编辑。

@Model.Title

是我的数据库中的一个属性,我希望能够使用 inline-editor 进行更改。

这段代码会产生同样的结果:

@using (Html.BeginForm())
{
    <h3  class="editable">@Model.Title</h3>

    <input type="text" id="testinput" name="testinput" />

    <input type="submit" value="submit">
   } 
Controller:


[HttpPost]
        public ActionResult FAQ(string testInput)
        {


            page.Title = testInput;

            return View();
        }

尽管如此,这并没有使用我想要的内联编辑器。

有没有办法将&lt;h3&gt; 视为textbox 允许我将其中的任何内容发送到控制器?

我想明确表示我不想直接将@model.title 发送给控制器。 我想发送通过单击&lt;h3&gt; 并使用内联编辑器更改它创建的值。

谢谢!

【问题讨论】:

  • 您可能需要拥有自己的框架或使用现有的框架来执行此操作,名为 x-editable。

标签: c# asp.net-mvc inline-editing


【解决方案1】:

当您以这种方式提交表单时,控制器将尝试将其匹配到正确的对象类型。如果您只想传回 1 或 2 个对象,请尝试使用操作链接。这些应该允许您传入名称以匹配您的控制方法的值。

【讨论】:

  • 感谢您的回答!我对 mvc 很陌生,如果你有时间,你介意发布一个代码示例吗?而且,当您说控制器将尝试与名称匹配时。这意味着如果我可以给 h3 一个名称,它会匹配吗?但我可以这样做吗?
【解决方案2】:

查看:

@model MvcApplication2.Models.ShopItem

@{
    ViewBag.Title = "Shop";
}

<h2>ShopView</h2>
@using (Html.BeginForm())
{
    <h3 class="editable">@Model.Name</h3>
    @Html.TextBox("Cost",0.00D,null)
    <input type="submit" title="Submit" />
}

型号:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication2.Models
{
    public class ShopItem
    {
        public int? Id { get; set; }
        public string Name { get; set; }
        public decimal? Cost { get; set; }

        public ShopItem()
        {
            Id = null;
            Name = "";
            Cost = null;
        }
    }
}

控制器:

    public ActionResult Shop()
    {
        ShopItem item = new ShopItem();
        return View(item);
    }

    [HttpPost]
    public ActionResult Shop(decimal Cost)
    {
        ShopItem item = new ShopItem();
        item.Cost = Cost;

        return View(item);
    }

如果你把它放在 HomeController 中,来测试它。您会看到我的输入具有强类型,并且与我的操作输入相匹配

【讨论】:

  • 感谢您的帮助,我尝试将您的代码粘贴到另一个项目中,看看是否可以从中学到一些东西...@html.textbox CS0121 出现错误:调用不明确在以下方法或属性之间:'System.Web.Mvc.Html.InputExtensions.TextBox(System.Web.Mvc.HtmlHelper, string, object, string)' 和 'System.Web.Mvc.Html.InputExtensions.TextBox(System .Web.Mvc.HtmlHelper, 字符串, 对象, System.Collections.Generic.IDictionary)'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多