I want to fill with a value of the @Html.Editor
when the page is loaded. Here is my failed attempt :
@Html.EditorFor(m => m, new { htmlAttributes = new { @class = "form-control" } })
At the top of the Razor page , I have this :
@model string
And this is my controller :
public ActionResult YeniBelge(string KimlikNo)
{
return View((object)KimlikNo);
}
It says value can't be null.
How can I make this correct? Thanks.
I suspect you are trying to assign a string that could be null to your model, which can never be null. Create a ViewModel class and use it instead:
public class MyViewModel {
public string TCKimlikNo { get; set; }
}
public ActionResult YeniBelge(string KimlikNo)
{
return View(new MyViewModel { KimlikNo = KimlikNo ?? "My Default Value" });
}
And then in your view:
@model MyViewModel
@Html.EditorFor(m => m.TCKimlikNo, new { htmlAttributes = new { @class = "form-control" } })
Fill your model with data in controller, then use
@Html.EditorFor(m=>m);
Like @vortex pointed out you need to use the EditorFor template.
@Html.EditorFor(model => model.TCKimlikNo, new { htmlAttributes = new { @class = "form-control" } })
If you have your model loaded at the top of the page this will fill in the form with the current value of the model field.
In your controller change to the following.
public class KimlikNoViewmodel
{
public string KimlikNo { get; set; }
}
public ActionResult YeniBelge (string KimlikNo)
{
KimlikNoViewmodel viewModel = new KimlikNoViewmodel();
viewModel.KimlikNo = KimlikNo;
return View(viewModel);
}
in your view I suspect that you are not finding the model. You need to include your project name when calling the Model.
@model YourProjectName.Controllers.KimlikNoViewmodel
I would suggest actually saving the View model we created within the Models folder under a View models file and then you would call the following instead.
@model YourProjectName.Models.KimlikNoViewmodel