简体   繁体   中英

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

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.

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();
        }
    }

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM