ASP.NET CORE Controller gets null value from input setting value via JS/JQuery

Viewed 43

I have a post controller to which I want to pass value set with JS or JQuery. So in my JS file I'm trying this before submit:

function anullUser() {
    $("#Mod").val("2");
    $("#depForm").submit();
}
@{
  @model IndexViewModel
}
<form id="depForm" class="formAddDepart" method="post">
<fieldset>
   /.../
  <input type="text" asp-for="Mod" />
</fieldset>
<div class="text-center">
  <button class="btn btn-warning" onclick="anullUser()" type="button">JS FUNC CALL</button>
</div>

Controller code:

public IActionResult Users(IndexViewModel model)
{ if(model.Mod == 2) { /.../} else {/.../} }

But in my controller I'm still getting NULL value for this property. I even have tried to do it and set this field with AJAX and still.

UPDATE: asp-for attribute generates for me ID and NAME attributes.

1 Answers

Pls allow me show you a sample:

@model WebAppMvc.Models.UserModel

<form id="depForm" method="post" asp-action="Create">
    <div>
        <label asp-for="id" class="control-label" >id:</label>
        <input asp-for="id" class="form-control" type="text" />
    </div>
    <div>
        <label asp-for="name" class="control-label">name:</label>
        <input asp-for="name" class="form-control" type="text" />
    </div>
     <button class="btn btn-warning" onclick="anullUser()" type="button">JS FUNC CALL</button>
</form>

@section Scripts{
    <script>
        function anullUser(){
            $("#name").val("2");
            alert(11);
            $("#depForm").submit();
        }

    </script>
}

In my sample, I had a model which contain id and name properties, so asp-for="id" will add attribute id="id" name="id" for the input. Then I had a post action in my controller which name is Create so I have to add asp-action="Create" in the <form>, if missing asp-action, no request will be send to the controller.

Then here's my Controller:

public class DataController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(int id, string name) {
            return Ok();
        }
    }

enter image description here

Related