ASP.NET MVC如何从视图传递单选按钮选中的值给控制器 [英] ASP.NET MVC How to Pass radiobutton selected value from view to controller

查看:749
本文介绍了ASP.NET MVC如何从视图传递单选按钮选中的值给控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组动态生成单选按钮。我只是想传达给我的控制器来获得选择的值。我尝试一些东西,但它不工作。我只能得到由表单用于不同的目的设置隐藏字段的值。
这些不工作 - 他们返回什么:

  VAR YourRadioButton2 =的Request.Form [WC];
字符串selectedTechnology =形式[WC];

有没有一种方法,我可以跨越到控制器获得所选择的单选按钮。这些单选按钮值是动态生成的。

查看

 <% - 有线选择 - %GT;
         &所述; TR>有线选择< / TR>
        <%为(VAR I = 0; I< subform.wiredchoices.Count;我++)%GT;
        <%{%GT;
            &所述; TR>                &所述; TD> <输入类型=电台NAME =WCVALUE =<%:subform.wiredchoices.ElementAt(我).WiredChoiceItem%GT; > < / TD>
                &所述; TD>&下;%:subform.wiredchoices.ElementAt(ⅰ).WiredChoiceItem%GT; < / TD>

控制器

 如果(rcpt.Form.Is(网络电话))
            {
                 的Response.Write(< BR />中+WC+ WC);                 清单<串GT; listValues​​ =新的List<串GT;();
                 的foreach(在Request.Form.AllKeys字符串键)
                 {
                         listValues​​.Add(的Request.Form [关键]);
                         的Response.Write(< BR />中+第一价值+的Request.Form [关键]);
                 }                 //循环每一个复选框
                 的foreach(在form.AllKeys VAR键2)
                 {
                             的Response.Write(< BR />中+第二个值+密钥2);
                 }
                //见单选框选择
                VAR YourRadioButton =的Request.Form [WC];
                的Response.Write(< BR />中+YourRadioButton+ YourRadioButton);
                字符串selectedTechnology =形式[WC];
                的Response.Write(< BR />中+YourRadioButton+ selectedTechnology);                VAR YourRadioButton2 =的Request.Form [WLC];
                的Response.Write(< BR />中+YourRadioButton+ YourRadioButton2);
                字符串selectedTechnology2 =形式[WLC];
                的Response.Write(< BR />中+YourRadioButton+ selectedTechnology2);                的Response.Write(< BR />中+的VoIP聘请);
                字符串wiredChoice =测试; //从单选按钮指定值这里
                字符串wiredLessChoice =测试; //从单选按钮指定值这里                // STORê提交页面返回
                计算机[RETURNURL] = fields.formType;                < / TR>
            <%}%GT;


解决方案

您code让我想起了使用Web形式的那些时光。啊!感谢上帝!。我们有ASP.NET MVC现在,我们可以在MVC干净的方式做到这一点。

让我们开始创建我们认为一个视图模型。

 公共类技术
{
    公众诠释标识{设置;得到; }
    公共字符串名称{设置;得到; }
}公共类CreateUserViewModel
{
    [需要]
    公众诠释? SelectedTechnology {设置;得到; }    公开名单<技术与GT;技术{设置;得到; }    //根据需要由视图中添加其他属性
    公共字符串用户名{设定;得到; }
}

现在在你的GET操作方法,创建这个视图模型的对象,加载科技集合属性并发送到视图。

 公众的ActionResult的Create()
{
  VAR VM =新CreateUserViewModel();
  vm.Technologies = GetTechnologyList();
  返回查看(VM);
}
私人列表<技术与GT; GetTechnologyList()
{
    //硬codeD的项目列表在这里,你可以将其替换为
    //从数据库表项目
    返回新的List<技术与GT;
    {
        新技术{ID = 1,名称=DSL},
        新技术{ID = 2,名称=VOIP},
        新技术{ID = 3,名称=拨号},
        新技术{ID = 4,名称=魔术师}
    };
}

现在在你的剃须刀观点,这是强类型我们CreateUserViewModel类

  @model ReplaceYourNamespaceHere.CreateUserViewModel
@using(Html.BeginForm())
{
    @ Html.ValidationSummary()   < H4>选择技术和LT; / H4>
    的foreach(在Model.Technologies VAR项)
    {
       < D​​IV> @ Html.RadioButtonFor(S = GT; s.SelectedTechnology,item.Id)@ item.Name< / DIV>
    }
    <输入类型=提交/>
}

这将渲染在项技术集合单选按钮的形式。当您提交表单,选择的技术的ID将被设置为张贴的形式/模型 SelectedTechnology 属性。

  [HttpPost]
公众的ActionResult创建(CreateUserViewModel模型)
{
    如果(ModelState.IsValid)
    {
        //选择技术标识是model.SelectedTechnology
        //做:保存和重定向
    }
    //刷新单选按钮列表数据
    model.Technologies = GetTechnologyList();
    返回查看(模型);
}

相信我,这就是:)

在这里输入的形象描述

如果您想preSELECT 1 radion按钮你创建(或编辑)视图中,可以设置 SelectedTechnology 属性值你想要的技术的Id选定的。

  VAR VM =新CreateUserViewModel();
 vm.Technologies = GetTechnologyList(); vm.SelectedTechnology = 3; //使用非硬codeD值替换 返回查看(VM);

I have a dynamically generated set of radio buttons. I just want to get the selected value across to my controller. I tried few things but it does not work. I can only get hidden field values set by the form for a different purpose. These do not work – they return nothing:

var YourRadioButton2 = Request.Form["wc"];
string selectedTechnology = form["wc"];

Is there a way I can get the selected radio buttons across to the controller. These radiobutton values are dynamically generated.

the View

<%--wired choices--%>
         <tr > Wired Choices </tr>
        <% for (var i = 0; i < subform.wiredchoices.Count; i++) %>
        <%{ %> 
            <tr>  

                <td> <input type="radio" name="wc" value="<%:    subform.wiredchoices.ElementAt(i).WiredChoiceItem %>" > </td>
                <td><%:    subform.wiredchoices.ElementAt(i).WiredChoiceItem %> </td>

The controller

if (rcpt.Form.Is("VoIP"))
            {
                 Response.Write("<br />" + "wc " + wc);

                 List<String> listValues = new List<String>();
                 foreach (string key in Request.Form.AllKeys)
                 {                    
                         listValues.Add(Request.Form[key]);
                         Response.Write("<br />" + "first values  " + Request.Form[key]);
                 }

                 // Loop through every checkbox
                 foreach (var key2 in form.AllKeys)
                 {
                             Response.Write("<br />" + "second values  " + key2);
                 }


                //See Radiobutton selections
                var YourRadioButton = Request.Form["wc"];
                Response.Write("<br />" + "YourRadioButton " + YourRadioButton);
                string selectedTechnology = form["wc"];
                Response.Write("<br />" + "YourRadioButton " + selectedTechnology);

                var YourRadioButton2 = Request.Form["wlc"];
                Response.Write("<br />" + "YourRadioButton " + YourRadioButton2);
                string selectedTechnology2 = form["wlc"];
                Response.Write("<br />" + "YourRadioButton " + selectedTechnology2);

                Response.Write("<br />" + "VoIP Hire ");
                String wiredChoice = "test"; //assign value from radio button here
                String wiredLessChoice = "test"; //assign value from radio button here

                // Stor e submitting page to return to
                ViewData["ReturnUrl"] = fields.formType;



                </tr>
            <%} %>

解决方案

Your code reminds me of those old days of using web forms. Ah ! Thank God!. We have ASP.NET MVC now and we can do this in a clean way in MVC.

Let's start creating a view model for our view.

public class Technology
{
    public int Id { set; get; }
    public string Name { set; get; }
}

public class CreateUserViewModel
{   
    [Required]
    public int? SelectedTechnology { set; get; }   

    public List<Technology> Technologies { set; get; }

    // Add other properties as needed by your view
    public string UserName { set; get; }
}

Now in your GET action method, create an object of this view model, Load the Technologies collection property and send that to the view.

public ActionResult Create()
{
  var vm = new CreateUserViewModel();
  vm.Technologies = GetTechnologyList();
  return View(vm);
}
private List<Technology> GetTechnologyList()
{
    //Hard coded a list of items here, You may replace it with 
    // Items from your db table
    return new List<Technology>
    {
        new Technology {Id = 1, Name = "DSL"},
        new Technology {Id = 2, Name = "VOIP"},
        new Technology {Id = 3, Name = "Dialup"},
        new Technology {Id = 4, Name = "Magic"}
    };
}

Now in your razor view, which is strongly typed to our CreateUserViewModel class

@model ReplaceYourNamespaceHere.CreateUserViewModel
@using (Html.BeginForm())
{
    @Html.ValidationSummary()

   <h4>Select a technology</h4>
    foreach (var item in Model.Technologies)
    {
       <div> @Html.RadioButtonFor(s => s.SelectedTechnology, item.Id) @item.Name</div>
    }
    <input type="submit"/>
}

This will render the form with radio buttons for the items in the Technologies collection. When you submit the form, the selected technology's id will be set to the SelectedTechnology property of the posted form/model.

[HttpPost]
public ActionResult Create(CreateUserViewModel model)
{
    if (ModelState.IsValid)
    {
        // Selected Technology Id is in model.SelectedTechnology
        // to do :Save and Redirect
    }
    //Reload the radio button list data
    model.Technologies = GetTechnologyList();
    return View(model);
}

Trust me, Here it is :)

If you want to preselect one radion button on your create( or edit ) view, you can set the SelectedTechnology property value the Id of the technology you want to selected.

 var vm = new CreateUserViewModel();
 vm.Technologies = GetTechnologyList();

 vm.SelectedTechnology = 3 ; //replace with a non-hard coded value 

 return View(vm);

这篇关于ASP.NET MVC如何从视图传递单选按钮选中的值给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆