简体   繁体   English

将值从隐藏字段传递到控制器MVC 4

[英]Passing value from hidden field to controller MVC 4

I basically have a table like this: 我基本上有一个这样的表:

<table class="table table-bordered table-responsive table-striped" id="tabelaIzostanci">
  <thead>
    <tr>
      <td><b>Ime i prezime</b></td>
      <td><b>Predmet</b></td>
      <td><b>Profesor</b></td>
      <td><b>Razlog</b></td>
      <td><b>Opravdano</b></td>
    </tr>
  </thead>
  <tbody>
    @foreach (var item in Model)
    {
      <tr>
        <td>@item.Ucenik.Ime @item.Ucenik.Prezime</td>
        <td>@item.Cas.Predmet.Naziv</td>
        <td>@item.Cas.Nastavnik.Ime @item.Cas.Nastavnik.Prezime</td>
        @if (item.Napomena == "")
        {
          <td>Napomena nije unesena.</td>
        }
        else
        {
          <td>@item.Napomena</td>
        }
        @if (item.Opravdano == false)
        {
          <td>Ne</td>
        }
        else
        {
          <td>Da</td>
        }
        <td>
          <form>
            <button type="button" onclick="toggle_visibility('toggle');" class="btn btn-primary">Opravdaj</button>
            <input  type="hidden" id="txtID" name="test" value="@item.OdsutnostID"/>
          </form>
        </td>
     </tr>
    }
  </tbody>
</table>

The button that I have is outside of table and looks like this: 我所拥有的按钮在表格外,如下所示:

<button style="float:right; width:100px;" type="button" onclick="CallMe()" class="btn btn-primary">Save</button>

The Javascript function that I'm using is: 我正在使用的Javascript函数是:

 function CallMe() {
       if ($('#txtID').val() !== '') {
           $.ajax({
               url: '/Controller/Action',
               type: 'POST',
               data: { txtID: $('#txtID').val(),
               success: function (data) {
                  Alert('Success');
               },
               error: function (error) {
                   alert('Error: ' + error);

               }
           });
       }

And my Action looks like this: 我的动作如下所示:

Public ActionResult Action(string txtID)
{
// checking whether the ID is there
}

The function is called, but the passed ID from View to Controller is always static, and somehow is always marked as "1". 调用了该函数,但是从View传递到Controller的ID始终是静态的,并且总是以某种方式标记为“ 1”。 If I click on the 2nd record in table which has the ID = 2, the passed ID is still =1; 如果单击表中ID = 2的第二条记录,则传递的ID仍为= 1;

I can't use the model because its being used for something else.. So my question is, is there any way I can pass the ID dynamically from View to Controller without having to use the model?? 我不能使用该模型,因为它已用于其他用途。所以我的问题是,有什么方法可以在不使用该模型的情况下将ID从View动态传递给Controller?

Or could someone help me out why is the ID always = 1? 或者有人可以帮我找出为什么ID总是= 1?

Thanks! 谢谢!

Edit: 编辑:

This is the button for showing and hiding the form: 这是显示和隐藏表单的按钮:

function toggle_visibility(id) {
       var e = document.getElementById(id);
       if (e.style.display == 'block') 
           e.style.display = 'none';
       else 
           e.style.display = 'block';
   }

From the comments your wanting to display a textarea when you click a button in a row, and then post the value of the text area and the OdsutnostID value of the item in the row to a controller method. 在注释中,当您单击一行中的按钮时想要显示文本区域,然后将文本区域的值和该行中该项的OdsutnostID值发布到控制器方法中。

Firstly, stop polluting your html with behavior and use Unobtrusive Javascript . 首先,停止使用行为污染html并使用Unobtrusive Javascript While you can add a hidden input for OdsutnostID and use relative selectors to extract the value, its easier to just delete this and add the value as a data- attribute. 虽然您可以为OdsutnostID添加隐藏的输入并使用相对选择器提取值,但将其删除并将值添加为data-属性会更容易。 The html for the last <td> element should be 最后一个<td>元素的html应该是

<td>
    <button type="button" class="edit btn btn-primary" data-id="@item.OdsutnostID">Opravdaj</button>
</td>

You have not shown the html for the textarea to edit the value of property Napomena but it should be something like 您尚未显示用于textarea的html来编辑属性Napomena的值,但应该类似于

<div id="form" style="display:none">
    <textarea id="napomena"><textarea>
    <button type="button" id="save">Save</button>
</div>

Then the scripts will be 然后脚本将是

var id = null;
var row = null;
var form = $('#form');
var textarea = $('#napomena');
var url = '@Url.Action("Action")';

$('.edit').click(function() {
  id = $(this).data('id'); // save the row id in global variable
  row = $(this).closest('tr'); // save current row in global variable
  textarea.val(row.children('td').eq(3).text()); // update the textarea with the current value
  form.show(); // display the 'form'
});

$('#save').click(function() {
    $.post(url, { id: id, text: textarea.val() }, function(data) {
        if(data) {
            row.children('td').eq(3).text(textarea.val()); // update the value in the row
            form.hide(); // hide the form
        }
    });
});

which will post back to 它将回发到

[HttpPost]
public ActionResult Action(string id, string text)
{
   // save the data
   return Json(true);
}

Side note: A few improvements you can make to the view 旁注:您可以对视图进行一些改进

  1. For the table header, use <th>Predmet</th> , not <td><b>Predmet</b></td> (the default style of th is bold, but it also means that its easier to style your header elements. 对于表头,请使用<th>Predmet</th> ,而不要使用<td><b>Predmet</b></td>th的默认样式为粗体,但这也意味着您可以更轻松地设置样式标头元素。
  2. Add a [DisplayFormat(NullDisplayText = "Napomena nije unesena")] attribute to property Napomena and then in the view its just <td>@Html.DisplayFor(m => item.Napomena)</td> (your if block is not necessary). 向属性Napomena添加[DisplayFormat(NullDisplayText = "Napomena nije unesena")]属性,然后在视图中将其仅为<td>@Html.DisplayFor(m => item.Napomena)</td>if阻止,则为您)必要)。

  3. Create a DisplayTemplate for bool which generates "Ne" or "Da" based on the value so that you can use just <td>@Html.DisplayFor(m => item.Opravdano, "nameOfYourTemplate")</td> rather than an if block. bool创建一个DisplayTemplate ,它根据该值生成"Ne""Da" ,以便您可以仅使用<td>@Html.DisplayFor(m => item.Opravdano, "nameOfYourTemplate")</td> if阻止。

you need to use a class instead and have a button near the class to trigger what you want to do 您需要改用一个类,并在该类附近有一个按钮来触发您想做的事情

<input type="hidden" class="txtIds" value="@item.ID" />

<button type="button" class="btn btn-primary triggerClosestId">trigger Id</button>

assuming you have jQuery you can do this 假设您有jQuery,则可以执行此操作

$('body').on('click', '.triggerClosestId' function () {
    var closestTxtId = $(this).closest('txtIds');
    $.ajax({
        url: '/Controller/Action',
        type: 'POST',
        data: { txtID: closestTxtId .val(),
        success: function (data) {
           alert('Success');
        },
        error: function (error) {
            alert('Error: ' + error);
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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