how to use radiobuttonlist in mvc4 - asp.net-mvc

I need to create a simple radio button list selection to choose from the following values:
Agree
Disagree
Not sure
How would we add it in the following razor view? Is it better to create an enum of these values in the QuestionModel and use foreach to bind with html helper.
Any example or ideas?
#model Survey.Models.Question
#using (Html.BeginForm("Index", "Home", new { QuestionId = Model.QuestionId }))
{
<h2>Survey</h2>
<fieldset>
<legend>Please Choose</legend>
<p>
Question ID:
#Model.QuestionId
</p>
<p>
Description:
#Model.Description
</p>
<input type="submit" value="Next" id="submitButton" />
</fieldset>
}

Using the ASP.NET Html Helpers, there are three various methods you can use for each of the different helpers supplied for radio buttons.
Method 1
A simple way to make a radio button list:
<div>
<label>
#Html.RadioButton("Answer", "Agree")
Agree
</label>
</div>
<div>
<label>
#Html.RadioButton("Answer", "Disagree")
Disagree
</label>
</div>
<div>
<label>
#Html.RadioButton("Answer", "Not Sure")
Not Sure
</label>
</div>
Method 2
The above code will post the checked value with a name of "Answer" to the server when you click Submit. If you would like to make this strongly typed, as you did with Model.QuestionId and Model.Description, you could add a Answer property to your model and do the following:
<div>
<label>
#Html.RadioButtonFor(m => m.Answer, "Agree")
Agree
</label>
</div>
<div>
<label>
#Html.RadioButtonFor(m => m.Answer, "Disagree")
Disagree
</label>
</div>
<div>
<label>
#Html.RadioButtonFor(m => m.Answer, "Not Sure")
Not Sure
</label>
</div>
Method 3
Finally, if you would like to get fancy, you can use an enum. Place the following in your controller:
public enum AnswerType {
Agree,
Disagree,
NotSure
}
Next, add the property to your model:
public AnswerType AnswerType { get; set; }
And then add the following to your view:
#Html.RadioButtonForEnum(m => m.AnswerType)
Hope this helps!

this will work
Radio button for model
#using (Html.BeginForm())
{
foreach (var department in Model.Departments)
{
#Html.RadioButtonFor(m => m.SelectedDepartment, department.Id) #department.Name
}
<input type="submit" value="Submit" />
}

In your viewmodel you could have a public int SelectedRating. You could make it a string and change the values from 114... to string values as well.
<div class="radio">
<label>
#Html.RadioButtonFor(x => x.SelectedRating, 114)
<span>Not Sure</span>
</label>
</div>
<div class="radio">
<label>
#Html.RadioButtonFor(x => x.SelectedRating, 115)
<span>Agree</span>
</label>
</div>
<div class="radio">
<label>
#Html.RadioButtonFor(x => x.SelectedRating, 116)
<span>Don't Agree</span>
</label>
</div>

Related

MVC 5, Using Checkbox for same model property twice in a page but inside different forms

Model property which I intend to use inside two forms
public class TestModel
{
[Display(Name = "Terms Accepted")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You need to accept terms and conditions to proceed!")]
public bool TermsAccepted { get; set; }
}
view Page
<form id="form1">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted, new { #id = "chk1" })
</div>
<div class="col-md-3">
<input type="submit" id="button1" onclick="return isFormValid('form1');" value="Submit Form 1"/>
</div>
</div>
</form>
<form id="form2">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted, new { #id = "chk2" }) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted)
</div>
<div class="col-md-3">
<input type="submit" id="button2" onclick="return isFormValid('form2');" value="Submit Form 2"/>
</div>
</div>
</form>
When this UI is rendered on the page, checkbox inside the 1st form do contains attributes for RangeDataAnnotation while checkbox inside 2nd form doesn't have any attributes for data annotation. So this results into 2nd form doesn't throw any validation on submission.
Html of checkboxes which get rendered on UI
Inside form 1:
<input name="TermsAccepted" class="input-validation-error" id="chk1" aria-describedby="TermsAccepted-error" type="checkbox" value="true" data-val="true" data-val-range-min="True" data-val-range-max="True" data-val-range="You need to accept terms and conditions to proceed!">
Inside form 2:
<input name="TermsAccepted" id="chk2" type="checkbox" value="true">
Any suggestions to make this work in both forms?

Gridmvc filtering without query in url

I'm using GridMvc and I'm filtering data. I'd like to hide filter query in the url like http://www.mypage.com/Overview?Name=yyy
My form is defined as:
<form class="form-inline" method="POST" action="#Url.Action("Filter", Request.QueryString)">
<div class="form-group>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name, new { placeholder = "Filter", #class = "form-control" })
<button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
And the action
[HttpPost]
public ActionResult Filter(FilterModel model)
But I always see the query. It's possible to hide query string?
You cound hide your query if you put all you data in hidden fields instead of Request.QueryString.
I mean if your Request.QueryString looks like param1=test1&param2=test2 you should render you view like this:
<form class="form-inline" method="POST" action="#Url.Action("Filter")">
<input type="hidden" name="param1" value="test1" />
<input type="hidden" name="param2" value="test2" />
<div class="form-group>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name, new { placeholder = "Filter", #class = "form-control" })
<button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
MVC binding will bind all hidden values on POST according to name property of this hidden inputs.
You should just fill inputs value (replace test1 and test2 with your values from Request.QueryString)

MVC foreach set item.ID to model.ID

I have a form that shows all the available hotel rooms, each room has a button that does a HttpPost if clicked, I have made a property in the BookingViewModel called 'RoomID'. I would like to assign the item.RoomID to Model.RoomID so I can use it in my controller to get the id from the selected room but i'm not sure how to achieve this.
ChooseRoom View
#foreach (var item in Model.AvailableRooms)
{
<li class="room-item clearfix">
<h5>#item.Name</h5>
<div class="room-list-left">
<img src="#item.Image" alt="" />
</div>
<div class="room-list-right">
<div class="room-meta">
<ul>
<li><span>Occupancy:</span> #item.Adults Adults #item.Childs Children</li>
#if (item.SmokingRoom)
{
<li><span>Smoking Allowed:</span> Yes</li>
}
else
{
<li><span>Smoking Allowed:</span> No</li>
}
</ul>
</div>
<div class="room-price">
<p class="price">From: <span>$#item.Price</span> / Night</p>
</div>
<div class="clearboth"></div>
#using (Html.BeginForm("chooseroom", "booking", FormMethod.Post))
{
<input class="button2" type="submit" value="Select Room" />
}
BookingController
[HttpPost]
public ActionResult ChooseRoom(BookingViewModel vm)
{
BookingViewModel bookingObj = GetBooking();
bookingObj.SelectedRoom = Repository.GetRoomByID(vm.RoomID);
return View("reservation", bookingObj);
}
Thank you for your time!
update your begin form as below
#using (Html.BeginForm("chooseroom", "booking", FormMethod.Post))
{
<input type="hidden" name="RoomId" value="#item.RoomID" />
<input class="button2" type="submit" value="Select Room" />
}
Just need to provide input tags having the same name as your ViewModel property.
You could add inputs in foreach loop , it should be inside form. Something like this <input name="Model.AvailableRooms[index].RoomID" value="Id Here"/>
Or if you want to select one Room you should use ajax and post id.
If I'm not wrong you form is in loop,so you could add hidden input with id
#Html.HiddenFor(c => c.AvailableRooms[index].RoomID)

Why Http Get action is called instead of Http post action?

I'm working with MVC and spent whole day getting stuck with this problem. Here is code at the controller:
public class CMController : Controller
{
public ActionResult SignUp()
{
return View("SignUpPage");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SignUp(User u)
{
if (ModelState.IsValid)
{
using (CmdbEntities dc = new CmdbEntities())
{
dc.Users.Add(u);
dc.SaveChanges();
ModelState.Clear();
u = null;
ViewBag.Message = ("Successfully sign on");
}
}
else
{
ViewBag.Message = ("Error");
}
return View("Welcome");
}
}
Here is the SignUpPage.cshtml view:
#using (Html.BeginForm("SignUp", "CM", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-group" style="padding:5px 50px">
<label> First name:</label>
<div>
#Html.TextBoxFor(model => model.FirstName, new {#class="form-control", placeholder="Enter first name", ID="FirstName"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label >Last name:</label>
<div>
#Html.TextBoxFor(model => model.LastName, new {#class="form-control", placeholder="Enter first name", ID="LastName"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label for="email">Email:</label>
<div>
#Html.TextBoxFor(model => model.Email, new {#class="form-control", placeholder="Enter email", ID="Email", type="email"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label >User name:</label>
<div>
#Html.TextBoxFor(model => model.UserName, new {#class="form-control", placeholder="Enter user name", ID="UserName"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label for="pwd">Password:</label>
<div>
#Html.TextBoxFor(model => model.Password, new {#class="form-control", placeholder="Enter password", ID="Password", type="password"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label for="pwd">Confirm password:</label>
<div>
#Html.TextBoxFor(model => model.ConfirmPassword, new {#class="form-control", placeholder="Re-enter password", ID="_password", type="password"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<div>
<input type="submit" ID="SignUp" class="btn btn-success" value="Sign Up" />
</div>
</div>
}
The problem is, when load page first time, the action SignUp() is called which is correct. But when submit the form, SignUp() is called again instead of the post action SignUp(User u).
One more problem, even the form has post method, when click submit the url contains input information just like get method, I don't understand.
Here is the page html source of form tag.
<form action="/CM/SignUp" method="post"><input name="__RequestVerificationToken" type="hidden" value="VJ0YcQr1Z-l3Qo717pRpZNT-QtL59G2EJXy2JQL8NFnOm-XoNnAD-8T-Itz3i1EboGj0bhpBf2G26ifxm4F5ZRyKimkOyZW1AxZ3ckPNuRk1" />
Please help, thank you.
Can you please try adding
[AllowAnonymous]
to the post method?
Did you activate global authorization anywhere
System.Web.Mvc.AuthorizeAttribute
?

Empty List When Data Is Posted To Action Method (ASP .Net MVC)

I have got a problem with submitting data to Post method.
I have a class similar to this:
public class A
{
public int Id{get; set;}
public string Name{get; set;}
public List<B> Bs {get; set;}
}
In the View I have a list of Bs object that I can add to the Bs property of class A without any problem. I can see the result without any problem in my Razor View as well.
The problem occurs when I post the final result to my Add Action Method to save them in my database.
When the final object is sent to my Action method the Bs property is completely empty. So what I did instead was to add that collection to a TempData dictionary and retrieved it in my Add Action method.
My question is simple why is my Bs property empty when its posted to my Edit action method ? The reason why I ask this is because in my AddBs action method I add my Bs to my Model and send it back to View and everything is find up to that point.
Edit:
#SLaks
This is the code I have in my View :
<% using (Html.BeginForm("Create", "A"))
{ %>
<%: Html.ValidationSummary(true) %>
<div class="editor-label">
<%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Name) %>
<%: Html.ValidationMessageFor(model => model.Name) %>
</div>
<% if (Model.Bs.Any())
{ %>
<h3>B List</h3>
<%= Html.Telerik().Grid(Model.Bs)
.Name("CheckedOrders")
.Columns(columns =>
{
columns.Bound(d => d.Id).Width(100);
columns.Bound(d => d.Name).Width(300);
})
.Footer(false)
%>
<% } %>
<br />
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
This is the HTML generated:
<form action="/Admin/BusinessType/Create" method="post">
<fieldset>
<div class="editor-label">
<label for="Name">Name</label>
</div>
<div class="editor-field">
<input class="text-box single-line" id="Name" name="Name" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>
<div class="t-widget t-grid" id="CheckedOrders"><table cellspacing="0"><colgroup><col style="width:100px" /><col style="width:300px" /></colgroup><thead class="t-grid-header"><tr><th class="t-header" scope="col">Id</th><th class="t-last-header t-header" scope="col">Name</th></tr></thead><tbody><tr><td>2</td><td class="t-last">Heeey</td></tr><tr class="t-alt"><td>3</td><td class="t-last">Testtttt</td></tr></tbody></table></div>
<br />
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</form>
The Code above shows perfectly fine in my Browser, I can even see the Bs list, but when I type a Name And Click on Create, the Bs list is empty.
I think the secret to this is in the view. I have a similar model in my app. In the view you have to format the names of the controls correctly:
<%
for (int i=0; i<model.Bs.Count; i++)
{
Html.TextBox( string.Format( "Bs[{0}].Property1OfB", i), model.Bs.Property1OfB );
Html.TextBox( string.Format( "Bs[{0}].Property2OfB", i), model.Bs.Property2OfB );
}
%>
The Add method will only receive whatever <input> elements are in the form that posted to it.

Resources