【问题标题】:how to pass text areas values to controller如何将文本区域值传递给控制器
【发布时间】:2016-06-08 10:04:19
【问题描述】:

我有一个包含多个循环生成的文本区域的视图。我想使用 jQuery 在表单提交上传递值。我使用下面的代码来调用动作结果:

var url = "/Template/DATA";
var form = $('<form action="' + url + '" method="post">' +
    '<input type="text" name="TemplateID" value="' + TemplateID + '" />' +
    '<input type="text" name="SectionID" value="' + SectionID + '" />' +
    '<input type="text" name="StartDate" value="' + StartDate + '" />' +
    '<input type="text" name="EndDate" value="' + EndDate + '" />' +
    // here i want to pass the values of the text areas to the action result
    '</form>');
$('body').append(form);
form.submit();

【问题讨论】:

  • 看起来您最好使用 AJAX 而不是动态构建表单的 HTML,将其附加到 DOM 并立即提交。
  • 视图的模型是什么?

标签: jquery asp.net-mvc asp.net-mvc-4 c#-4.0


【解决方案1】:

使用 html/jquery/ajax 怎么样?

<form id="form" action="" method="post">
    <input type="text" id="template" name="TemplateID" value="" />
    <input type="text" id="section" name="SectionID" value="" />
    <input type="text" id="start" name="StartDate" value="" />
    <input type="text" id="end "name="EndDate" value="" />
    <button type="submit">Submit</button>
</form>;

在文档加载时为 from 赋值并序列化数据以进行发送。

jQuery(document).ready(function ($) {

    $('#template').val('Template');
    $('#section').val('section');
    $('#start').val('start');
    $('#end').val('end');

$('#form').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        url: 'js/ajax.php',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        beforeSend: function () {
        },
        success: function (data, textStatus, xhr) {
            console.log(data);
            console.log(data.status);
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log(textStatus);
            console.log(errorThrown);
            console.log(data.status);
        }
    });
});
});

然后像访问任何其他帖子数据一样访问 php 中的数据

if($_POST){

    $template = $_POST['template'];
    $section = $_POST['section'];
    $start = $_POST['start'];
    $end = $_POST['end'];
    /** Do whatever with this data */ 

    $result = $template . $section . $start . $end
    echo json_encode(array('status' => 'ok', 'result' => $content));

} else {
    echo json_encode(array('status' => 'error'));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多