简体   繁体   中英

Passing value from view to controller

OK, i asked a very similar question recently and I got good answers back. However, I probably did not express my problem accurately so I will give it another go here:

This is my view

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

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

} 

The <h3> has the class "editable" which in this case means it can be edited by an inline-editor.

@Model.Title

Is a properties from my database that I would like to be able to change with the inline-editor .

This code would generate the same result:

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

Allthough, this does not use the inline-editor which I would like.

Is there maybe a way to treat the <h3> as if it was a textbox allowing me to send whatever is in there to the controller?

I want to make clear that I do NOT want to send @model.title to the controller directly. I want to send the value created by clicking on the <h3> and using the inline-editor to change it.

Thank you!

When you submit a form in this fashion the controller will try and match it to the correct object type. If you want to just pass back 1 or 2 objects try using the action links. These should allow you to pass in the values with names to match your control methods.

View:

@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" />
}

Model:

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;
        }
    }
}

Controller:

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

If you put this in the HomeController, to test it. You will see my input has a strong type, and matches my action inputs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM