Prefill Html Editor Asp.net MVC

2019-08-21 03:01发布

问题:

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.

回答1:

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"  } })


回答2:

Fill your model with data in controller, then use

@Html.EditorFor(m=>m);


回答3:

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.



回答4:

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