【问题标题】:Updating the View with Model changes via Ajax Post by calling a javascript function通过调用 javascript 函数通过 Ajax Post 更新具有模型更改的视图
【发布时间】:2020-03-11 23:01:54
【问题描述】:

我使用 Ajax 调用来更新我的模型值,然后让新值显示在视图中。这是我的代码。在这段代码中,我正在调用 GetText 方法并更新模型值。如何在 html 中显示新模型值。请帮忙

public class EmpModel
{
public string EmpClaim {get;set;}
}


 public IActionResult EmpClaim()
 {
    return View();
 }
 [HttpPost]
    public ActionResult GetText(EmpModel model)
    {
        model.EmpClaim = "New Text" // This should be shown in view

         return Json(data);

    }

HTML 文件

@model Test.Models.EmpModel
<div>
<input type="text" name="Claim" class="form-control" id="TxtClaim"  asp-for="Claim" data-role="text"/>
</div>

<div>
    <input type="button" onclick="changeText()" id="changeButton"  />
</div>

Javascript

<script>
 function changeText()
{
 var url = '@Url.Action("GetText", "EmpDoc")';
    $.post(url, $('form').serialize(), function (view) {
        $("#TxtClaim").val(); // How can I update the TxtClim with model.EmpClaim "New Text" 
    });
}

</script>

【问题讨论】:

    标签: javascript json ajax asp.net-core http-post


    【解决方案1】:

    您可以使用return Content() 将字符串返回给ajax 函数。

        [HttpPost]
        public IActionResult GetText(EmpModel model)
        { 
           model.EmpClaim = "New Text" // This should be shown in view  
            return Content(model.EmpClaim); 
        }
    

    Js:

     <script>
         function changeText()
         {
         var url = '@Url.Action("GetText", "EmpDoc")';
            $.post(url, $('form').serialize(), function (view) {
                $("#TxtClaim").val(view); // How can I update the TxtClim with model.EmpClaim "New Text"
            });
        }
        </script>
    

    结果如下:

    注意

    在您的情况下,模型没有a key field,因此在更新数据时,您无法确定要更新哪条数据。进一步的操作可能需要您修改模型设计。

    您可以参考this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多