将值从视图传递到控制器

本文关键字:控制器 视图 | 更新日期: 2023-09-27 17:59:08

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

这是我的观点

@using (Html.BeginForm())
{
<h3  class="editable">@Model.Title</h3>
<input type="submit" value="submit">   
} 

<h3>具有类"editable",这在本例中意味着它可以由内联编辑器编辑。

@Model.Title

是我的数据库中的一个属性,我希望能够使用内联编辑器进行更改。

此代码将生成相同的结果:

@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();
        }

不过,这并没有使用我想要的内联编辑器。

是否有一种方法可以将<h3>视为textbox,允许我将其中的任何内容发送到控制器

我想明确表示,我不想直接将@model.title发送到控制器。我想发送通过点击<h3>并使用内联编辑器来更改它所创建的值。

谢谢!

将值从视图传递到控制器

当您以这种方式提交表单时,控制器将尝试将其匹配到正确的对象类型。如果您只想传递回1或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中,对它进行测试。你会看到我的输入有一个强类型,并且与我的操作输入

匹配