C# 将字符串值作为int从视图传递给控制器

C# 将字符串值作为int从视图传递给控制器,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,让我拥有以下视图模型: public class ViewModel { public string SomeValue {get; set;} public int CountryId {get; set;} } public class YourViewModel { public string CountryName {get; set;} public string CountryId {get; set;} } 和国家名单 var count

让我拥有以下视图模型:

public class ViewModel
{
     public string SomeValue {get; set;}
     public int CountryId {get; set;}
}
public class YourViewModel
{
     public string CountryName {get; set;}
     public string CountryId {get; set;}
}
和国家名单

var countryList = new[]{new[]{Country="Russia", Value=1},new[]{Country="USA", Value=2},new[]{Country="Germany", Value=3} }
我想用这些字段创建一个表单。问题是国家/地区输入必须是文本框

所以我不能只编写类似于
Html.TextBoxFor(m=>m.CountryId)
的东西。这些任务的最佳实践是什么?是隐藏场还是其他什么


编辑

界面看起来像:

    SomeValue: |_______|

    Country:   |_______|

                |Submit button|
在“国家”字段中,我们只能键入国家名称。在SomeValue中,另一个值与什么无关(您可以想象SomeValue不存在)。

@使用(Html.BeginForm(“Index”,“Home”){

页码:
@Html.TextBox(“CountryId”)

} [HttpPost] 公共行动结果索引(int countryId) { CountryId=CountryId; }
@使用(Html.BeginForm(“Index”,“Home”){

页码:
@Html.TextBox(“CountryId”)

} [HttpPost] 公共行动结果索引(int countryId) { CountryId=CountryId; }
我不完全理解你的问题。我说用户可以输入国家id和名称,对吗

最好将视图模型发送到视图。假设您拥有以下视图模型:

public class ViewModel
{
     public string SomeValue {get; set;}
     public int CountryId {get; set;}
}
public class YourViewModel
{
     public string CountryName {get; set;}
     public string CountryId {get; set;}
}
您的操作方法可能如下所示:

public ActionResult Index()
{
     YourViewModel viewModel = new YourViewModel();

     return View(viewModel);
}

[HttpPost]
public ActionResult Index(YourViewModel viewModel)
{
     // Check viewModel for nulls
     // Whatever was typed in on the view you have here,
     // so now you can use it as you like
     string country = viewModel.CountryName;
     string id = viewModel.CountryId;

     // Do whatever else needs to be done
}
您的视图可能如下所示:

@model YourProject.DomainModel.ViewModels.YourViewModel

@using (Html.BeginForm())
{
     <div>
          @Html.TextBoxFor(x => x.CountryName)<br />
          @Html.ValidationMessageFor(x => x.CountryName)
     </div>

     <div>
          @Html.TextBoxFor(x => x.CountryId)<br />
          @Html.ValidationMessageFor(x => x.CountryId)
     </div>

     <button id="SaveButton" type="submit">Save</button>
}
public class CountryViewModel
{
    public string SomeValue { get; set; }
    public string SomeMoreFormData { get; set; }
    public string Country { get; set; }
}
[HttpPost]
public ActionResult Index(CountryViewModel viewModel)
{
    var countryId = GetCountries()
                    .Where(c => c.Country.ToLower() == viewModel.Country.ToLower())
                    .Select(c => c.Id)
                    .SingleOrDefault();

    if (countryId != 0)
        return RedirectToAction("Thanks");
    else
        ModelState.AddModelError("CountryNotSelected", "You have selected an invalid country.");

    return View(viewModel);
}
@model YourProject.DomainModel.ViewModels.YourViewModel
@使用(Html.BeginForm())
{
@Html.TextBoxFor(x=>x.CountryName)
@Html.ValidationMessageFor(x=>x.CountryName) @Html.TextBoxFor(x=>x.CountryId)
@Html.ValidationMessageFor(x=>x.CountryId) 拯救 }

我希望这能有所帮助。

我不能百分之百地理解你的问题。我说用户可以输入国家id和名称,对吗

最好将视图模型发送到视图。假设您拥有以下视图模型:

public class ViewModel
{
     public string SomeValue {get; set;}
     public int CountryId {get; set;}
}
public class YourViewModel
{
     public string CountryName {get; set;}
     public string CountryId {get; set;}
}
您的操作方法可能如下所示:

public ActionResult Index()
{
     YourViewModel viewModel = new YourViewModel();

     return View(viewModel);
}

[HttpPost]
public ActionResult Index(YourViewModel viewModel)
{
     // Check viewModel for nulls
     // Whatever was typed in on the view you have here,
     // so now you can use it as you like
     string country = viewModel.CountryName;
     string id = viewModel.CountryId;

     // Do whatever else needs to be done
}
您的视图可能如下所示:

@model YourProject.DomainModel.ViewModels.YourViewModel

@using (Html.BeginForm())
{
     <div>
          @Html.TextBoxFor(x => x.CountryName)<br />
          @Html.ValidationMessageFor(x => x.CountryName)
     </div>

     <div>
          @Html.TextBoxFor(x => x.CountryId)<br />
          @Html.ValidationMessageFor(x => x.CountryId)
     </div>

     <button id="SaveButton" type="submit">Save</button>
}
public class CountryViewModel
{
    public string SomeValue { get; set; }
    public string SomeMoreFormData { get; set; }
    public string Country { get; set; }
}
[HttpPost]
public ActionResult Index(CountryViewModel viewModel)
{
    var countryId = GetCountries()
                    .Where(c => c.Country.ToLower() == viewModel.Country.ToLower())
                    .Select(c => c.Id)
                    .SingleOrDefault();

    if (countryId != 0)
        return RedirectToAction("Thanks");
    else
        ModelState.AddModelError("CountryNotSelected", "You have selected an invalid country.");

    return View(viewModel);
}
@model YourProject.DomainModel.ViewModels.YourViewModel
@使用(Html.BeginForm())
{
@Html.TextBoxFor(x=>x.CountryName)
@Html.ValidationMessageFor(x=>x.CountryName) @Html.TextBoxFor(x=>x.CountryId)
@Html.ValidationMessageFor(x=>x.CountryId) 拯救 }

我希望这能有所帮助。

当下拉列表看起来更合适时,这当然是一个奇怪的要求,但我们以前都有过奇怪的要求。:)这里有一个简单的例子,希望它能展示出你需要知道的一切,以便让它工作

首先,一个将国家名称与id关联的简单模型:

public class CountryModel
{
    public int Id { get; set; }
    public string Country { get; set; }
}
现在控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(string country)
    {
        var countryId = GetCountries()
                        .Where(c => c.Country.ToLower() == country.ToLower())
                        .Select(c => c.Id)
                        .SingleOrDefault();

        if (countryId != 0)
            return RedirectToAction("Thanks");
        else
            ModelState.AddModelError("CountryNotSelected", "You have selected an invalid country.");

        return View();
    }

    private List<CountryModel> GetCountries()
    {
        return new List<CountryModel>
        {
            new CountryModel { Id = 1, Country = "Russia" },
            new CountryModel { Id = 2, Country = "USA" },
            new CountryModel { Id = 3, Country = "Germany" }
        };
    }
}
然后从这里开始,POST方法将更改为如下内容:

@model YourProject.DomainModel.ViewModels.YourViewModel

@using (Html.BeginForm())
{
     <div>
          @Html.TextBoxFor(x => x.CountryName)<br />
          @Html.ValidationMessageFor(x => x.CountryName)
     </div>

     <div>
          @Html.TextBoxFor(x => x.CountryId)<br />
          @Html.ValidationMessageFor(x => x.CountryId)
     </div>

     <button id="SaveButton" type="submit">Save</button>
}
public class CountryViewModel
{
    public string SomeValue { get; set; }
    public string SomeMoreFormData { get; set; }
    public string Country { get; set; }
}
[HttpPost]
public ActionResult Index(CountryViewModel viewModel)
{
    var countryId = GetCountries()
                    .Where(c => c.Country.ToLower() == viewModel.Country.ToLower())
                    .Select(c => c.Id)
                    .SingleOrDefault();

    if (countryId != 0)
        return RedirectToAction("Thanks");
    else
        ModelState.AddModelError("CountryNotSelected", "You have selected an invalid country.");

    return View(viewModel);
}

其次,请注意我是如何通过
GetCountries()
创建国家列表的。如果您的需求发生变化,这将允许您稍后轻松地重构此列表,以便从数据库中获取国家/地区列表。

当下拉列表看起来更合适时,这当然是一个奇怪的需求,但我们以前都有奇怪的需求。:)这里有一个简单的例子,希望它能展示出你需要知道的一切,以便让它工作

首先,一个将国家名称与id关联的简单模型:

public class CountryModel
{
    public int Id { get; set; }
    public string Country { get; set; }
}
现在控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(string country)
    {
        var countryId = GetCountries()
                        .Where(c => c.Country.ToLower() == country.ToLower())
                        .Select(c => c.Id)
                        .SingleOrDefault();

        if (countryId != 0)
            return RedirectToAction("Thanks");
        else
            ModelState.AddModelError("CountryNotSelected", "You have selected an invalid country.");

        return View();
    }

    private List<CountryModel> GetCountries()
    {
        return new List<CountryModel>
        {
            new CountryModel { Id = 1, Country = "Russia" },
            new CountryModel { Id = 2, Country = "USA" },
            new CountryModel { Id = 3, Country = "Germany" }
        };
    }
}
然后从这里开始,POST方法将更改为如下内容:

@model YourProject.DomainModel.ViewModels.YourViewModel

@using (Html.BeginForm())
{
     <div>
          @Html.TextBoxFor(x => x.CountryName)<br />
          @Html.ValidationMessageFor(x => x.CountryName)
     </div>

     <div>
          @Html.TextBoxFor(x => x.CountryId)<br />
          @Html.ValidationMessageFor(x => x.CountryId)
     </div>

     <button id="SaveButton" type="submit">Save</button>
}
public class CountryViewModel
{
    public string SomeValue { get; set; }
    public string SomeMoreFormData { get; set; }
    public string Country { get; set; }
}
[HttpPost]
public ActionResult Index(CountryViewModel viewModel)
{
    var countryId = GetCountries()
                    .Where(c => c.Country.ToLower() == viewModel.Country.ToLower())
                    .Select(c => c.Id)
                    .SingleOrDefault();

    if (countryId != 0)
        return RedirectToAction("Thanks");
    else
        ModelState.AddModelError("CountryNotSelected", "You have selected an invalid country.");

    return View(viewModel);
}

其次,请注意我是如何通过
GetCountries()
创建国家列表的。如果您的需求发生变化,这将允许您稍后轻松地重构此文件,以便从数据库中获取国家/地区列表。

好吧……在您的代码中,用户只需查看国家/地区id(1,2,3,4,5),但我需要一个解决方案,用户可以在其中写入文本USA,单击提交,然后在控制器中获取国家/地区id。好吧……在您的代码中,用户只需查看国家/地区id(1,2,3,4,5)但我需要一个解决方案,用户可以通过点击submit(提交)向文本USA(美国)写入,我们可以在controller(控制器)中获得国家Id。请澄清,您想在文本框中键入
德国
,提交表单,并想在controller(控制器)操作中获得3?你不认为
DropdownList
谁是更好的选择吗?或者textbox是必需的?@Mohayemin是的,textbox是必需的。为什么不像其他网站一样使用下拉列表呢?然后问题就解决了。让我们澄清一下,您想在文本框中键入
Germany
,提交表单,然后想在控制器操作中获得3?你不认为
DropdownList
谁是更好的选择吗?或者textbox是必需的?@Mohayemin是的,textbox是必需的。为什么不像其他网站一样使用下拉列表呢?然后问题就解决了。不,用户只能键入国家名称。国家是如何生成的?如果是这样的话,你为什么不修改我的代码,去掉国家id?如何生成国家id是我问题的重点。如果我们只是从视图中取出country id字段,那么我们如何在viewmodel中获得它?我不明白您想做什么。我会将国家添加到数据库中,让它返回下一个可用的id。不,用户只能键入国家名称。然后如何生成国家?如果是这样的话,你为什么不修改我的代码,去掉国家id?如何生成国家id是我问题的重点。如果我们只是从视图中取出country id字段,那么我们如何在viewmodel中获得它?我不明白您想做什么。我会把国家添加到数据库中,让它返回下一个可用的id。