How to Expose <select asp-for> to Javascript

Coreysan 1,811 Reputation points
2022-06-07T04:01:37.817+00:00

I have an extension method to get a value from a select item control, and then it assigns the value to a property in a class:

<select asp-for="@Model.Inventory.CategoryId" asp-items="Model.Categories.ToSelectListItem(Model.Inventory.CategoryId)" class="form-control"></select>  

This works very well with a standard asp.net form, but I need to use FormData, and call my POST method with ajax.
But now I don't know how to expose the integer value from @默 .Inventory.CategoryId to Javascript.

Can it be done?

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rena Ni - MSFT 2,066 Reputation points
    2022-06-07T05:18:26.177+00:00

    Hi @Coreysan ,

    Here is a whole working demo about how to get the selected data by using js:

    View:

    @model TestVM  
    <form asp-action="Login" asp-controller="Home" method="post">  
       <select asp-for="@Model.Inventory.CategoryId" class="form-control">  
           <option value="0">aaa</option>  
           <option value="1">bbb</option>  
       </select>  
      
       <button type="button" id="PostBtn" class="btn btn-sm btn-primary">Post</button>  
    </form>  
    

    JS in view:

    var selectedId= $("#Inventory_CategoryId").val();    //get the selected value  
    

    208943-image.png

    Model design:

    public class TestVM  
    {  
        public Inventory Inventory { get; set; }  
            
    }  
    public class Inventory  
    {  
        public int CategoryId { get; set; }  
    }  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Rena

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.