Skip to content
Advertisement

I have simple MVC APP which makes HttpGet request and passes array of 7 random unknown numbers into View [ SOLVED]

I started a MVC app which has a basic task to create 7 random numbers from 0 to 9 at positions between 1 and 7 inclusive (never starting with 0). At first the numbers are changed with “X” marks. When the user attempts to click on “Submit” button and if he managed to guess correctly one number on a given position ( e.g Column 1 with Number 8) – the relevant “X” at the given position has to become the “Number” which was written as input.

Picture describing what I got is below.

  1. Controller
namespace SecretNumberGame.Controllers
{
    public class GameController : Controller
    {
        private readonly ISecretNumberService service;

        public GameController(ISecretNumberService _service)
        {
            this.service = _service;
        }
        [HttpGet]
        public async Task<IActionResult> GetSecretNumber()
        {
            SecretNumberViewModel modelNumber = await service.GetSecretNumberAsync();
            return View(modelNumber);
        }        

        [HttpPost]
        public async Task<IActionResult> FindSecretNumber(string nums, int num, int col)
        {
            var arrayNumbers =  nums.Split(" ").ToArray();
            SecretNumberViewModel modelNumber = new SecretNumberViewModel();
            modelNumber.SecretNum = nums;
            modelNumber.Num = num;  
            modelNumber.Col = col;
            for (int i = 0; i < arrayNumbers.Length; i++)
            {
                if (arrayNumbers[i]==num.ToString())
                {
                    modelNumber.ShowValue[i] = true;
                    modelNumber.SecretNumArray[i]=num.ToString();
                    break;
                }
            }
            return Json(new { data = modelNumber });
        }                

    }
}
  1. ViewModel
namespace SecretNumberGame.Services.Models
{
    public class SecretNumberViewModel
    {
        public string SecretNum { get; set; }
        public string[] SecretNumArray { get; set; } = new string[] {"X","X","X","X","X","X","X" };

        public bool[] ShowValue { get; set; } = new bool[7];
        public int Col { get; set; }
        public int Num { get; set; }
    }
}
  1. View
@model SecretNumberViewModel
@{
    ViewBag.Title = "Secret Number";
}
<h2 class="text-center">@ViewBag.Title</h2>
<hr />

<div class="row">
    <div class="bg-info w-25 rounded-pill">
        <h5>Secret Number : @Model.SecretNum</h5>
           
    </div>
</div>
<hr />
    <div class="container text-md-center">
        <table width="100%" height="100%" align="center" class="table-bordered border-5 table-success">
            <thead >
            <tr>
                    @for (int i = 1; i <= Model.SecretNum.Split(" ").ToArray().Length; i++)
                    {
                     <td align="center" valign="middle" class="bg-success">
                        <h5 id="item1">@i</h5>
                     </td>
                    }
                    

                </tr>
            </thead>
            <tbody>
                <tr>
                @for (int i = 0; i < Model.SecretNum.Split(" ").ToArray().Length; i++)
                {
                    <td>
                        <h1>X</h1>
                    </td>
                }
                    
                </tr>
            </tbody>
        </table>
    </div>
    <hr />
    <br />
    <form method="post">
    
        <div  class="form-control card-body bg-primary bg-opacity-25">
        
        <label >Column</label>        
        <br />
        <input name="col" type="number" min="1" max="7" placeholder="1-7">
        <br />
        <label >Number</label>
        <br />
        <input name="num" type="number" min="0" max="9" placeholder="0-9" />
        <hr />
        <input asp-action="FindSecretNumber" asp-controller="Game" asp-route-nums="@(Model.SecretNum)" type="submit"
               class="btn btn-info btn btn-outline-primary rounded-pill" />        
        </div>
    </form>


I manage to get all parameters returned correctly into the HttpPost method. I can handle and return a json with the appropriate array of numbers. By that, I mean (“8” “X” “X” “X” “X” “X” “X”).

When I try to submit again – everything starts at “X” again, and I think I need some AJAX call from this Controller to be sent after clicking on “Submit” button. After that I need to receive the result from AJAX and somehow replace these “X” with the apprppriate number.

I expect if guessed correctly – to replace all “X” with the appropriate numbers. I watched a lot of tutorials, and I can’t get the idea how to make this MVC to work properly with AJAX / JS – I want this to happen like single page app after click on the button and change all the “X” when guessed.

If not guessed, I will add some logic. If I make “HttpPost” method in Controller “return View(modelNumber)” instead of Json , then I can get this, which partially solves my problem:

I just need your help to find the best and simplest way to achieve this result.

Edit: Here is explanation on how’s the secret number populatedInitial secret number population

Advertisement

Answer

If you just want to change the “X X X X X X X X” to specific secret, here is a working demo below:

View

@model SecretNumberViewModel
@{
    ViewBag.Title = "Secret Number";
}
<h2 class="text-center">@ViewBag.Title</h2>
<hr />
<div class="row">
    <div class="bg-info w-25 rounded-pill">
        <h5>Secret Number : @Model.SecretNum</h5>
    </div>
</div>
<hr />
<div class="container text-md-center">
    <table width="100%" height="100%" align="center" class="table-bordered border-5 table-success">
        <thead>
            <tr>
                @for (int i = 1; i <= Model.SecretNum.Split(" ").ToArray().Length; i++)
                {
                    <td align="center" valign="middle" class="bg-success">
                        <h5 id="item1">@i</h5>
                    </td>
                }
            </tr>
        </thead>
        <tbody>
            <tr id="SecretRow">     @*give the tr id*@
                @for (int i = 0; i < Model.SecretNum.Split(" ").ToArray().Length; i++)
                {
                    <td>     
                        <h1>X</h1>
                    </td>
                }
            </tr>
        </tbody>
    </table>
</div>
<hr />
<br />
<form method="post">
    <div class="form-control card-body bg-primary bg-opacity-25">
        <label>Column</label>
        <br />
             @*give the input id*@
        <input id="col" name="col" type="number" min="1" max="7" placeholder="1-7">
        <br />
        <label>Number</label>
        <br />
             @*give the input id*@
        <input id="num" name="num" type="number" min="0" max="9" placeholder="0-9" />
        <hr />   
                @* change the input type to button*@
        <input onclick="changeSecret()" type="button"
               class="btn btn-info btn btn-outline-primary rounded-pill" />
    </div>
</form>
@section Scripts
{
    <script>
        function changeSecret()
        {
            var data= {
            col: $("#col").val(),
            num: $("#num").val(),
            nums:'@Model.SecretNum'
            };
            $.ajax({
                url: "/Game/FindSecretNumber",
                type: 'post',
                dataType: 'json',
                data:data,
                success:function(res){
                    var index = res.data.col-1;
                    $("#SecretRow").find('td').eq(index).find("h1").text(res.data.num);
                       
                }
            })
        }
    </script>
}

Controller

[HttpPost]
public async Task<IActionResult> FindSecretNumber(string nums, int num, int col)
{
    SecretNumberViewModel modelNumber = new SecretNumberViewModel();
    modelNumber.SecretNum = nums;
    modelNumber.Num = num;
    modelNumber.Col = col;
    return Json(new { data = modelNumber });
}

Result: enter image description here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement