使用ajax部分视图调用从输入获取视图中的模型数据/对象的最简单方法

本文关键字:视图 模型 方法 数据 对象 最简单 获取 ajax 调用 输入 使用 | 更新日期: 2023-09-27 18:05:42

你好,我在谷歌上找到了一个解决我的问题的方法,每个链接都给我带来了asp表单解决方案,或者不要求表单输入的解决方案,这个问题有表单输入,我似乎找不到帮助的链接,我要求的很简单:通过ajax调用从用户输入中获取数据。

视图(index.cshtml):

@model UIPractice.Models.ModelVariables
<!-- Use your own js file, etc.-->
<script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<div id="div1">
@Html.BeginForm(){ @Html.TextBoxFor(x => x.test1, new { style = "width:30px" })}


<button id="hello"></button>
</div>
<div id="result1"></div>
 <script type="text/javascript">
//Job is to load partial view on click along with model's objects
$(document).ready(function () {
    $('#hello').click(function () {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("HelloAjax", "Home")',
data: $('form').serialize(),
            success: function (result) {
                $('#result1').html(result);
            }
        });
    });
});

模型(ModelVariables.cs):

 public class ModelVariables
{
//simple string that holds the users text input
   public string test1 { get; set; }
}

控制器(HomeController.cs):

 // GET: Home
    public ActionResult Index()
    {
        ModelVariables model = new ModelVariables();
        return View(model);
    }
    public ActionResult HelloAjax(ModelVariables model)
    {

        ViewBag.One = model.test1;`
        return PartialView("_MPartial", model);
    }

局部视图(_MPartial.cshtml):

@model UIPractice.Models.ModelVariables

@{
<div>
    <!--if code runs, i get a blank answer, odd...-->
    @Model.test1
    @ViewBag.One
</div>    
}

所以继续复制/粘贴代码来运行,你会注意到当你点击按钮时你什么也没有得到,用户文本输入,奇数…

使用ajax部分视图调用从输入获取视图中的模型数据/对象的最简单方法

我发现了一些问题。

您使用Html.BeginForm的代码不正确。应该是

@using(Html.BeginForm())
{ 
   @Html.TextBoxFor(x => x.test1, new { style = "width:30px" })
   <button id="hello">Send</button>
}
<div id="result1"></div>

这将生成正确的表单标签。

现在对于javascript部分,您需要防止默认的表单提交行为,因为您正在进行ajax调用。你可以使用jQuery的preventDefault方法。

$(document).ready(function () {
    $('#hello').click(function (e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("HelloAjax", "Home")',
            data: $('form').serialize(),
            success: function (result) {
                $('#result1').html(result);
            } 
            ,error: function (a, b, c) {                     
                    alert("Error in server method-"+c);
            }
        });
    });
});

另外,你可以考虑在脚本部分中添加你的页面级jquery事件处理程序(假设你有一个名为"scripts"的部分,它在jquery加载后在布局中被"RenderSection"调用。

在你的布局中

<script src="~/PathToJQueryOrAnyOtherLibraryWhichThePageLevelScriptUsesHere"></script>
@RenderSection("scripts", required: false)

,在你的个人视图中,

@section scripts
{
  <script>
  //console.log("This will be executed only after jQuery is loaded
  $(function(){
       //your code goes here
  });
  </script>
}