Search code examples
c#asp.net-mvcasp.net-coremodel-view-controller

Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>.Model.get returned null. Error. How to fix this?


I have the following view

@model CaseConverterModel

<h1 class="text-center fw-bold">Title Case Converter</h1>
<h4 class="text-center">Smart Title Capitalization Tool</h4>

<div class="row">
    <div class="col-md-3">
    </div>
    <div class="col-md-6">
        <form asp-action="ConvertToTitleCase">
            <textarea id="txtText" class="form-control" style="width:100%"></textarea>
            <br />
            <input type="submit" value="Convert" class="btn btn-primary" />

            <hr />
            <p>@Model.OutPutText</p>
        </form>

    </div>
    <div class="col-md-3">
    </div>
</div>

Following Controller

   public IActionResult Index()
    {
        return View();
    }

[HttpPost]
public IActionResult ConvertToTitleCase(string inputText)
{
    var obj = new CaseConverterModel();
    obj.OutPutText = "this is test";
    return View(nameof(Index), obj);
}

Here is the Model

public class CaseConverterModel
{
    public string InputText { get; set; }
    public string OutPutText { get; set; }
}

When I run it it shows following error message enter image description here

How to solve this?


Solution

  • @Yong Shun said is right.

    Your <p>@Model.OutPutText</p> need the model value, but in your (get) Index() method , you don't pass the model.

    Could you try to use @Html.DisplayFor ?

    Below is a work demo, hope it can help you. Make some change in your form like below:

            <form asp-action="ConvertToTitleCase">
                <textarea id="txtText" name="inputText" class="form-control" style="width:100%"></textarea>
                <br />
                <input type="submit" value="Convert" class="btn btn-primary" />
    
                <hr />        
                <p>@Html.DisplayFor(m => m.OutPutText)</p>
            </form>
    

    result:

    enter image description here