Home > Mobile >  How to pass model from razor view to controller using ajax call?
How to pass model from razor view to controller using ajax call?

Time:09-30

I am building an asp.net Core 5 application. I want to send a Model from Razor Page to My Controller named AJAX through AJAX Call. I need to know the syntax. My model is bound to my page form. I have tried passing a single string but am unable to find value at the other end. I have the same name in the JSON string and the parameter name in the controller method. I have tried FromBody and many other ways to do so. My Network shows data is passed by I received null in parameter. Please help

enter image description here

My test code.

@model dotnet5MVC.Models.IndexEmail
@{
    Layout = null;
}
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256- iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>

<div class="form-group row mb-3">
    <div class="col">
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-user-circle"></i></span>
            <input asp-for="@Model.Name" class="form-control" id="displayname" type="text" name="name" placeholder="Name" />
        </div>
    </div>

</div>


<div class="form-group row">
    <div class="col">
        <input value="Send" onclick="SendEmail()" class="btn btn-primary" type="submit" />
    </div>
</div>


<script>
 function SendEmail() {
        var jsonData = JSON.stringify({ Name: $("#displayname").val(), Subject: $("#subject").val(), EmailAddress: $("#emailaddress").val(), MessageBody: $("#messagebody").val() });
        $("body").addClass("loading");
        $.ajax({

            type: "POST",
            url: '@Url.Action("SendGrid_SendEmail", "Ajax")',
            contentType: "application/json; charset=utf-8",
            dataType:"json",
            data: jsonData ,
            error: function (xhr, status, error) {
                }
            }).done(function (data) {

            $("body").removeClass("loading");

            });
}
</script>

My test code in Controller.

public class AjaxController : Controller
{
    [HttpPost]
    public async Task<JsonResult> SendGrid_SendEmail([FromBody]IndexEmail data)
    {
        var aa = data;
        return Json("ok");
    }
}

CodePudding user response:

I have found the solution. See below-updated code.

  1. Form HTML, Only for Name field. All other fields have similar HTML. The only difference is Id

              <div class="form-group row mb-3">
              <div class="col">
              <div class="input-group"><span class="input-group-addon">
              <i class="fa fa-user-circle"></i></span>
               <input id="displayname" asp-for="IndexEmail.Name" class="form- 
               control" type="text" name="name" placeholder="Name" />
               </div>
              </div>
              </div>
    
  2. AJAX Call on Send Button

    function SendEmail() {
         if ($("form").valid()) {
             var jsonData = { EmailAddress: $("#emailaddress").val(), MessageBody: $("#messagebody").val(), Name: $("#displayname").val(), Subject: $("#subject").val() };
    
             $("body").addClass("loading");
             $.ajax({
    
                 type: "POST",
                 url: "Ajax/SendGrid_SendEmail",
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 data: JSON.stringify(jsonData),
                 error: function (xhr, status, error) {
                 }
             }).done(function (data) {
                 debugger;
                 $("body").removeClass("loading");
    
             });
         }
     }
    
  3. Controller

     [HttpPost]
     public async Task<bool> SendGrid_SendEmail([FromBody] IndexEmail jsonData)
     {
         try
         {}
      }
     catch (Exception e)
         {
         }
    
  4. Json Data Received in Controller Action Parameter Json Received

  • Related