Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  167] [ 3]  / answers: 1 / hits: 18701  / 9 Years ago, tue, july 14, 2015, 12:00:00

New to MVC--was never much of a front-end Web developer (mostly backend), so I'm not too privy to good design on the front-end. Now, I'm trying to use MVC without much original WebForm knowledge...that being said, please give me some pointers/links/good ideas on how to handle the following:



I have a textbox field that I want to show/hide based on a checkbox. I have these fields in my View @using (Html.BeginForm()...



Should I change the attribute on the text box in a javascript or controller action? If I use javascript, I'm having a hard time getting to the values in my beginform, but if I use controller action, I'm not sure how/what to pass to/from in my controller action.


More From » asp.net-mvc

 Answers
83

I like using jQuery if I want to manipulate DOM.



Here the example -



enter



View



@using (Html.BeginForm())
{
@Html.CheckBoxFor(model => model.MyBooleanValue)
<br />
@Html.TextBoxFor(model => model.MyTextValue)
<br />
<input type=submit value=Submit />
}

<script src=//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js></script>
<script>
$(function () {
$(#MyBooleanValue).click(function () {
if ($(this).is(':checked')) {
$(#MyTextValue).show();
}
else {
$(#MyTextValue).hide();
}
});
});
</script>


Controller



public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
MyBooleanValue = true
};
return View(model);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (model.MyBooleanValue)
{
string text = model.MyTextValue;
}

return View(model);
}
}


Model



public class MyViewModel
{
public bool MyBooleanValue { get; set; }
public string MyTextValue { get; set; }
}


FYI: I suggest watch few videos training (free course at ASP.NET MVC 5 Fundamentals) or read a book or two before starting it. Otherwise, you will get frustrated.


[#65809] Sunday, July 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
finn

Total Points: 154
Total Questions: 88
Total Answers: 82

Location: Lithuania
Member since Mon, Nov 16, 2020
4 Years ago
;