Prefill Html Editor Asp.net MVC

2019-08-21 02:40发布

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.

4条回答
做自己的国王
2楼-- · 2019-08-21 03:00

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"  } })
查看更多
SAY GOODBYE
3楼-- · 2019-08-21 03:07

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.

查看更多
Fickle 薄情
4楼-- · 2019-08-21 03:22

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
查看更多
对你真心纯属浪费
5楼-- · 2019-08-21 03:27

Fill your model with data in controller, then use

@Html.EditorFor(m=>m);
查看更多
登录 后发表回答