Radiobutton Selected value not pass to the controller - c#

I have 2 radio buttons with mvc view.When i do form submit that Checkboxes values not pass to the controller.
I have a form submit like this,
#using(Html.BeginForm("Index","Employee",FormMethod.Get))
{
<b>Search by :</b>#Html.RadioButton("Searchby", "EmpName",true)<text>Name</text>
#Html.RadioButton("Searchby", "IsPermanant")<text>Id</text><br />
#Html.TextBox("Search");
<input type="submit" value="Search" />
}
I have a controller
public ActionResult Index(string Search, bool Searchby)//In here searchby is null
{
}

Your creating a radio button group that will post back either the value "EmpName" or "IsPermanant", yet you are trying to bind it to a boolean property.
Either change the parameter bool Searchby to string Searchby or change the radio buttons to return true or false

You probably need to use the FormMethod.Post instead of FormMethod.Get
#using(Html.BeginForm("Index","Employee",FormMethod.Post))
{
<b>Search by :</b>#Html.RadioButton("Searchby", "EmpName",true)<text>Name</text>
#Html.RadioButton("Searchby", "IsPermanant")<text>Id</text><br />
#Html.TextBox("Search");
<input type="submit" value="Search" />
}
The second parameter of method RadioButton is value you want to pass to your controller. In your example you are passing EmpName or IsPermanant as string but your controller is expecting boolean. Changing the controller to accept string would allow you to pass the values you have for radio buttons.
public ActionResult Index(string Search, string Searchby)
{
}

Related

MVC 4 Dropdownlist Pass value by button?

I have created a dropdownlist using html helper.
It's able to get the value and bind to dropdown.
How can i pass the selected dropdown value to controller?
My View:
#Html.DropDownList("Language", new SelectList(ViewBag.LangList, "Text", "Value"))
<input type="button" class="btn" title="Filter By Language"
value="Filter By Language" onclick="location.href='#Url.Action("SURV_Answer_Result", "SURV_Answer",
new { Survey_ID = Model[0].Survey_ID, Language = ViewBag.LangList })'" />
My Controller to get Language and bind into dropdown:
public ActionResult SURV_GetLanguage(int Survey_ID)
{
var getlanguagelist = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new { r, s } by r.Qext_Language into grp
select grp.FirstOrDefault();
foreach (var item in getlanguagelist.ToList())
{
List<SelectListItem> langResult = new List<SelectListItem>();
foreach (var item2 in getlanguagelist)
{
SelectListItem temp = new SelectListItem();
temp.Text = item2.r.Qext_Language;
temp.Value = item2.r.Qext_Language;
langResult.Add(temp);
}
ViewBag.LangList = langResult;
}
return View(ViewBag.Langlist) ;
}
And i want pass the Language to the controller below:
public ActionResult SURV_Answer_Result(int Survey_ID, string Language)
{
List<AnswerQuestionViewModel> viewmodel = new List<AnswerQuestionViewModel>();
SURV_GetLanguage(Survey_ID);
// do whatever i want...
}
Your button in the view istype="button" and you have attached a onclick event which will just redirect to the SURV_Answer_Result passing the original ViewBag property back to the method (which will not bind to string Language because its List<SelectListItem>.
You need a form with FormMethod.Get
#using (Html.BeginForm("SURV_GetLanguage", "ControllerName", new { Survey_ID = Model[0].Survey_ID }, FormMethod.Get))
{
#Html.DropDownList("Language", (Enumerable<SelectListItem>)ViewBag.LangList)
<input type="submit" ... />
}
Notes:
The Survey_ID has been added to the form as a route value
ViewBag.LangList is Enumerable<SelectListItem> which is all that
is required by the DropDownList() helper so there is no point in
the extra overhead of creating another SelectList from it
(SelectList IS Enumerable<SelectListItem>)
The code you have used would work if you change the method signature on the controller to public ActionResult SURV_GetLanguage(int Survey_ID, string Language = null). You could then test for nulls and process as necessary.
However it would be better to wrap the dropdownlist inside a form, and use a POST request. Something like:
#using (Html.BeginForm("SURV_GetLanguage","ControllerName",FormMethod.Post))
{
#Html.DropDownList("Language", new SelectList(ViewBag.LangList, "Text", "Value"))
<input type="submit" class="btn" />
}
Then in the controller you could have a new method:
[HttpPost]
public ActionResult SURV_GetLanguage(string Language)
{
//Do whatever you want with language.
}
There are two ways,
1) You can put your dropdown and submit button into a form containing action parameter. On button press, your form will be submitted to its action. Your action must contain a parameter with name 'Languages'. It will give you selected value.
All the parameters of action, if matching to 'name' property of controls, will contain their values on form submit.
2) You can get selected value from dropdown by using jquery and then use either window.location or build url for form's action and call submit.

ASP.NET - two types of users that register in one registration form?

I'm building a website application that will have two different types of users, let's call one A and the other is B. They have some similar data, such as: 'name', 'password', etc., and the rest are different. I have done 2 tables for them separately because I need it like that, but I have an idea and I'm not sure whether I can do it!
The idea is that when the user goes to the Registration Page, they will be shown a registration form that contains the data that is similar between A and B, and then I will let the user check a check box indicating whether it's an A user or a B user. Depending on what they have chosen, the rest of the form will appear in the same page to let them continue registration.
I'm working with ASP.NET in C# and I'm wondering whether this idea is applicable? My problem is with the check box - how do I let the rest of the registration form appear depending on what they have chosen, then add it to the right table?
MVC?
2 options:
Either have both of the forms in your html, with attribute ID = 'form a', 'form b'. Make sure to submit the forms to different actions.
Show hide either form like this:
$('.radioBtn').click(function() {
var formType = $(this).val();
//alert(formType);
if (formType == "A") {
$('#FormA').show();
$('#FormB').hide();
} else {
$('#FormB').show();
$('#FormA').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form style="display: none" id="FormA" action="/actionA">
.... your html FORM A
</form>
<form style="display: none" id="FormB" action="/actionB">
.... your html FORM B
</form>
<input type="radio" name="typeOfForm" class="radioBtn" value="A">Form A
<input type="radio" name="typeOfForm" class="radioBtn" value="B">Form B
Also, if you want to show the forms just don't do display:none
inside the form have a which is set to no display until a user makes a choice.
--
OR
Use ajax, have your forms as partial views and upload them into a target div once the radio is clicked. (let us know if this is needed)
I think the first show / hide is enough for your case. There is no reason to upload since the form is just an empty set of inputs.
EDIT
Next, we catch these submitted forms in your controller. Each form will submit to the same action, or you wish different actions, this does not make a difference - your preference.
option 1.
The form on the page:
<form action='#Url.Action("YourRegisterAction", "controller")' >
<input type="hidden" name="FormType" value="A"/> <!--place B for B form-->
<input type="text" name="Name" placeholder ="enter your name"/>
<input type="text" name="Password" placeholder ="enter your name"/>
<input type="submit" value="Register Me!"/>
</form>
The controller
[HttpPost]
public ActionResult YourRegisterAction(char formType, string name, string password)
{
if (formType == 'A')
bool success = BL.Server.Instance.SaveMyNewUserToDBTypeA(name, password);
else if (formType == 'B')
bool success = BL.Server.Instance.SaveMyNewUserToDBTypeB(name, password);
return View("ThankYou", success);
}
option 2.
Use models.
The model
public class YourRegisterAction
{
public string Name { get; set; }
public string Password { get; set; }
public char FormType { get; set; }
}
The view
#model Domain.UI.Models
<form action='#Url.Action("YourRegisterAction", "controller")' >
#Html.HiddenFor(m=>m.FormType)
#Html.TextBoxFor(m=>m.Name)
#Html.TextBoxFor(m=>m.Password)
<input type="submit" value="Register Me!"/>
</form>
The controller
[HttpPost]
public ActionResult YourRegisterAction(RegisterViewModel m)
{
if (m.FormType == 'A')
bool success = BL.Server.Instance.SaveMyNewUserToDBTypeA(m.Name, m.Password);
else if (m.FormType == 'B')
bool success = BL.Server.Instance.SaveMyNewUserToDBTypeB(m.Name, m.Password);
return View("ThankYou", success);
}
After you have the submitted form in your controller. Just persist in the DB as you normally would.
Also please use #using (Html.BeginForm) instead of the form tags. You can find plenty of info on this here.
Like #Fel said on Comment,
You should better use the radio buttons,
Let call them as rb1 and rb2, grouping the radio buttons by give them a same groupname.
And Also Give AutoPostBack="True" for both, So that only you can change the rest of the fields while the radiobutton is checked.
Create the rest of forms for both users separately as Panels p1 for A and p2 for B
In the rb1_checkedchanged event, show p1,
In the rb2_checkedchanged event, show p2
When click the Submit button
if (rb1.checked=true)
display form for A;
store it in a Table for A;
else
display form for B;
store it in a Table for B;
Hope this Helps...
All the Best...

ASP.NET Model Binding can I give submit button a value and retrieve that value when its clicked?

Is it possible to use Model binding to get value of a button in the POST action method when its clicked on. I have a complex type and I wanted to have the user click on a button and retrieve the value of that button so I can use it to update the value of the complex type in the DB.
Note that at this point I have already saved the entity into the database and all that is left is to get a way to update properties of the complex type.
If there is a recommended way to do that am willing to adopt that.
Thanks in advance.
You can use multiple submit buttons with different values to specify the way of update model.
#using (Html.BeginForm("MultipleCommand", "Home", FormMethod.Post, new { id = "submitForm" }))
{
.
.
.
<button type="submit" id="btnSave" name="Command" value="create">Save</button>
<button type="submit" id="btnSubmit" name="Command" value="update">Submit</button>
}
public ActionResult(ComplexModel model, string Command)
{
if(Command == "create")
{
}
else if(Command == "update")
{
}
else
{
// Default action
}
}
For more info read Handling multiple submit buttons on the same form - MVC Razor.
Do something like this
public ActionResult Index(string submit)
////Your action while clicking the button and in the view button name should be submit
{
//// The string submit will have the value of the button
}

How to execute 3 different controller methods from the same view

I have created a C# ASP.NET MVC application. In the Index view, i have added 3 buttons, when each button is clicked i want to execute 3 different functions from the Index controller.
Index View that resides in the Home folder
#using (Html.BeginForm()) {
<input type="submit" value="b1" />
<input type="submit" value="b2" />
<input type="submit" value="b3" />
}
Home Controller
public ActionResult Button1Click()
{
return View();
}
public ActionResult Button3Click()
{
return View();
}
public ActionResult Button2Click()
{
return View();
}
When each button is clicked how can i write code to execute the correct controller method ?
If you are posting then you can put each button in a separate form:
#using (Html.BeginForm("Button1Click","Index")) {
<input type="submit" value="b1" />
}
#using (Html.BeginForm("Button2Click","Index")) {
<input type="submit" value="b2" />
}
#using (Html.BeginForm("Button3Click","Index")) {
<input type="submit" value="b3" />
}
If there is no data to post, as shown in your method, and you still want to have all buttons in the same form then you can do an ajax post (this does not make sense though but hey I'm basing it on the code you gave in your question), with this though you may want to change your buttons from a submit into a button (input type="button").
$("#b1").click(function(){
$.post('/index/button1click', function() {
});
});
$("#b2").click(function(){
$.post('/index/button2click', function() {
});
});
$("#b3").click(function(){
$.post('/index/button3click', function() {
});
});
If you want to do a GET instead of a post then just replace .post with .get.
In MVC you need to remove the (Asp.Net) idea of linking button clicks to actions. ASP.Net is event driven MVC uses the classic HTTP REST approach.
So the buttons aren't actions, the buttons submit actions. The action that is submitted is controlled by your form. So your form POSTs data to the controller, using a HTTP post.
Now it's not clear what your trying to achieve here. You appear to be returning different views from each action. So using the REST idea, you should be a GETing not a POSTing (your getting HTML). So the simplest idea is to turn your input(submit) into Anchor tag, i.e. a HTTP GET:
#Html.ActionLink("Button1Click")
etc.
MVC doesn't work like Webforms where you have a ButtonClick event.
Do you want to post any values to the controller?
If not, you can use a link that you can style like a button. Use the buildin Html extensions.
//For links
#Html.ActionLink("Button1Text","Button1Click")
#Html.ActionLink("Button2Text","Button2Click")
#Html.ActionLink("Button3Text","Button3Click")
//If you need more styling options
Button1
Button2
Button3
That way you don't need any javascript or multiple forms in your view. You'll have to add some styling in your CSS files.
One easy way to execute different actions on different button within the same form is to distinguish button click by their name:
Example code is:
View:
#using (Html.BeginForm("MyMethod","Controller"))
{
<input type="submit" value="b1" name="b1" />
<input type="submit" value="b2" name="b2" />
<input type="submit" value="b3" name="b3" />
}
Controller:
[HttpPost]
public ActionResult MyMethod(string b1, string b2, string b3)
{
if (b1 != null)
{
return Button1Click();
}
else if (b2 != null)
{
return Button2Click();
}
else
{
return Button3Click();
}
}
public ActionResult Button1Click()
{
return RedirectToAction("Index");
}
public ActionResult Button3Click()
{
return RedirectToAction("Index");
}
public ActionResult Button2Click()
{
return RedirectToAction("Index");
}

How to change drop-down list on select

I have a dropdownlist that is being populated by a sql server, I am using Visual Studio 2010, cshtml, with razor as well as using the MVC pattern to create this project. What I am trying to do is when someone selects a value from the dropdown list on change it will update the page with information about that book.
I need help with the three things below:
user selects a book from the dropdownlist how to get the Book Name back to the controller
The server (retrieve the information from the server about the book) and
Back to view to be displayed.
I started with getting the dropdown poplulated.
My View looks like this
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
My Controller:
public ActionResult Index()
{
ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());
return View();
}
A dropdown list can't cause the page to post back to your controller on its own. You need to do one of two things:
Add a submit button so that the user changes the dropdown and then clicks a button to view the results.
Use javascript to submit the form on the element's change event.
Either way, you will need to wrap the dropdown/submit button in a form.
Option 1
<form>
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
<input type="submit" value="Show results" />
</form>
Option 2
<script type="text/javascript">
// assuming you're using jQuery
$(function() {
$('#UserSelectedValue').change(function() {
$(this).parent('form').submit();
});
});
</script>
<form>
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
<input type="submit" value="Show results" />
</form>
Your controller code would then become something like:
public ActionResult Index(string bookName)
{
ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());
if (!string.IsNullOrWhiteSpace(bookName))
{
ViewData["Books"] = _context.BookName.Where(b => b.Book_Name == bookName).ToList();
}
return View();
}

Categories