本文介绍了字符串作为模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这本来应该是一件容易的事:

I thought this should have been an easier task :

直到今天,Asp.Net MVC仍无法提供针对这种情况的灵巧解决方案:

It seems till this day Asp.Net MVC couldn't provide a neat solution on this case:

如果您要将简单的字符串作为模型传递,而不必定义更多的类和东西……有什么想法吗?

将简单字符串作为模型传递

在这里,我试图建立一个简单的字符串模型.

here I'm trying to have a simple string model.

我遇到此错误:

"Value cannot be null or empty" / "Parameter name: name"

视图:

@model string
@using (Html.BeginForm())
{
        <span>Please Enter the code</span>
        @Html.TextBoxFor(m => m) // Error Happens here
        <button id="btnSubmit" title="Submit"></button>
}

控制器:

public string CodeText { get; set; }

public HomeController()
{
    CodeText = "Please Enter MHM";
}

[HttpGet]
public ActionResult Index()
{
    return View("Index", null, CodeText);
}

[HttpPost]
public ActionResult Index(string code)
{
    bool result = false;
    if (code == "MHM")
        result = true;

    return View();
}

推荐答案

可以将字符串包装在视图模型对象中:

Either wrap the string in a view model object:

型号:

public class HomeViewModel
{
    public string CodeText { get; set; }
}

控制器:

private HomeViewModel _model;

public HomeController()
{
    _model = new HomeViewModel { CodeText = "My Text" };
}

[HttpGet]
public ActionResult Index()
{
    return View("Index", _model);
}

查看:

@Html.TextBoxFor(m => m.CodeText);

使用EditorForModel:

@Html.EditorForModel()

这篇关于字符串作为模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 05:59
查看更多