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

时间:2022-12-02 14:40:04

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 2 and 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 2 in qty

但是在控制器部分我得到了qty的旧值。但是我需要在数量上更新值2

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

5 个解决方案

#1


8  

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)

#2


3  

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),您可以输入名称(respectecting case)“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");
}

#3


2  

your link is generated when the page loads therefore 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

您也可以将其包装在一个表单中,并为id,productid和unitrate隐藏字段

Here's a sample for 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

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

#4


1  

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

#5


0  

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.

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

#1


8  

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)

#2


3  

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),您可以输入名称(respectecting case)“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");
}

#3


2  

your link is generated when the page loads therefore 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

您也可以将其包装在一个表单中,并为id,productid和unitrate隐藏字段

Here's a sample for 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

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

#4


1  

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

#5


0  

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.

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