C# 如何将文本框值从视图传递到 MVC 4 中的控制器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12954806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:05:29  来源:igfitidea点击:

How to pass a textbox value from view to a controller in MVC 4?

c#asp.net-mvcasp.net-mvc-4

提问by bala3569

Here i am fetching the value from database and showing it in a input field

在这里,我从数据库中获取值并将其显示在输入字段中

<input type="text" id="ss" value="@item.Quantity"/>

and the value fetching from database is 1.Then i am changing the input field value to 2and passing that value to the controller in a action click

并且从数据库中获取的值是1。然后我将输入字段值更改为2并将该值传递给控制器​​单击操作

 <a id="imgUpdate"  href="@Url.Action("Update", "Shopping", new { id = Request.QueryString["UserID"], productid = item.ProductID, qty = item.Quantity, unitrate = item.Rate })"> 

But in the controller part i am getting that old value1 for qty.But i need that updated value 2in qty

但在控制器部分我得到的是old value1对qty。但我需要updated value 2qty

public ActionResult Update(string id, string productid, int qty, decimal unitrate)
        {
            if (ModelState.IsValid)
            {
                int _records = UpdatePrice(id,productid,qty,unitrate);
                if (_records > 0)
                {
                    return RedirectToAction("Index1", "Shopping");
                }
                else
                {
                    ModelState.AddModelError("","Can Not Update");
                }
            }
            return View("Index1");
        }

Any suggestion?

有什么建议吗?

EDIT:

编辑:

     @using (Html.BeginForm("Update", "Shopping", FormMethod.Post))
     {

                @Html.Hidden("id", @Request.QueryString["UserID"] as string)
                @Html.Hidden("productid", item.ProductID as string)
                @Html.TextBox("qty", item.Quantity)
                @Html.Hidden("unitrate", item.Rate)

                <input type="submit" value="Update" />
     }

回答by Eonasdan

your link is generated when the page loadstherefore it will always have the original value in it. You will need to set the link via javascript

您的链接是在页面加载时生成的,因此它始终具有原始值。您需要通过 javascript 设置链接

You could also just wrap that in a form and have hidden fields for id, productid, and unitrate

你也可以只换行的形式,并具有隐藏字段idproductidunitrate

Here's a samplefor ya.

这是给你的样本

HTML

HTML

<input type="text" id="ss" value="1"/>
<br/>
<input type="submit" id="go" onClick="changeUrl()"/>
<br/>
<a id="imgUpdate"  href="/someurl?quantity=1">click me</a>

JS

JS

function changeUrl(){
   var url = document.getElementById("imgUpdate").getAttribute('href');
   var inputValue = document.getElementById('ss').value;
   var currentQ = GiveMeTheQueryStringParameterValue("quantity",url);
    url = url.replace("quantity=" + currentQ, "quantity=" + inputValue);
document.getElementById("imgUpdate").setAttribute('href',url)
}

    function GiveMeTheQueryStringParameterValue(parameterName, input) {
    parameterName = parameterName.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\?&]" + parameterName + "=([^&#]*)");
    var results = regex.exec(input);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

this could be cleaned up and expanded as you need it but the example works

这可以根据需要进行清理和扩展,但示例有效

回答by webdeveloper

You can use simple form:

您可以使用简单的形式:

@using(Html.BeginForm("Update", "Shopping"))
{
    <input type="text" id="ss" name="qty" value="@item.Quantity"/>
    ...
    <input type="submit" value="Update" />
}

And add here attribute:

并在此处添加属性:

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)

回答by Pierluc SS

When you want to pass new information to your application, you need to use POST form. In Razor you can use the following

当您想将新信息传递给您的应用程序时,您需要使用 POST 表单。在 Razor 中,您可以使用以下内容

View Code:

查看代码:

@* By default BeginForm use FormMethod.Post *@
@using(Html.BeginForm("Update")){
     @Html.Hidden("id", Model.Id)
     @Html.Hidden("productid", Model.ProductId)
     @Html.TextBox("qty", Model.Quantity)
     @Html.TextBox("unitrate", Model.UnitRate)
     <input type="submit" value="Update" />
}

Controller's actions

控制器的动作

[HttpGet]
public ActionResult Update(){
     //[...] retrive your record object
     return View(objRecord);
}

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
{
      if (ModelState.IsValid){
           int _records = UpdatePrice(id,productid,qty,unitrate);
           if (_records > 0){                    {
              return RedirectToAction("Index1", "Shopping");
           }else{                   
                ModelState.AddModelError("","Can Not Update");
           }
      }
      return View("Index1");
 }

Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity)you can either have an input with the name (respectecting case) "Quantity"or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:

请注意,或者,如果您想使用,@Html.TextBoxFor(model => model.Quantity)您可以输入带有名称的输入(对应大小写),"Quantity"或者您可以更改 POST Update() 以接收对象参数,该参数与您的严格类型视图的类型相同。下面是一个例子:

Model

模型

public class Record {
    public string Id { get; set; }
    public string ProductId { get; set; }
    public string Quantity { get; set; }
    public decimal UnitRate { get; set; }
}

View

看法

@using(Html.BeginForm("Update")){
     @Html.HiddenFor(model => model.Id)
     @Html.HiddenFor(model => model.ProductId)
     @Html.TextBoxFor(model=> model.Quantity)
     @Html.TextBoxFor(model => model.UnitRate)
     <input type="submit" value="Update" />
}

Post Action

发布操作

[HttpPost]
public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well 
   if(TryValidateModel(rec)){
        //update code
   }
   return View("Index1");
}

回答by sssD

I'll just try to answer the question but my examples very simple because I'm new at mvc. Hope this help somebody.

我只是尝试回答这个问题,但我的例子非常简单,因为我是 mvc 的新手。希望这对某人有帮助。

    [HttpPost]  ///This function is in my controller class
    public ActionResult Delete(string txtDelete)
    {
        int _id = Convert.ToInt32(txtDelete); // put your code           
    }

This code is in my controller's cshtml

此代码在我的控制器的 cshtml 中

  >   @using (Html.BeginForm("Delete", "LibraryManagement"))
 {
<button>Delete</button>
@Html.Label("Enter an ID number");
@Html.TextBox("txtDelete")  }  

Just make sure the textbox name and your controller's function input are the same name and type(string).This way, your function get the textbox input.

只需确保文本框名称和控制器的函数输入具有相同的名称和类型(字符串)。这样,您的函数就会获得文本框输入。

回答by michael.2.williams

Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter

在您的视图中尝试以下操作以检查每个的输出。当第二次调用视图时,第一个更新。我的控制器使用键 ShowCreateButton 并具有可选参数 _createAction 和默认值 - 您可以将其更改为您的键/参数

@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton