Checking a radio button - asp.net-mvc-3

I want to check a radio button based on the culture which is set in the "culture" variable in the #helper method. During debugging, I know the the variable is set; it's just not checking the English or Spanish radio button.
Could someone tell me how I can do this based on the below code or if there is an easier way for the code, that would be fine too. I'm using MVC 3 Razor.
#helper selected(string c, string culture)
{
if (c == culture)
{
#:checked="checked"
}
}
<script type="text/javascript">
$(function () {
$("input[type='radio']").click(function () {
$(this).parents("form").submit();
});
// highlight selected language
$("input[type='radio']:checked").next().css("font-weight", "bold");
});
</script>
#using (Ajax.BeginForm("SetCulture", "Home", new AjaxOptions { UpdateTargetId = "setCulture" }))
{
<fieldset id="setCulture">
<legend>#Resources.SelectCulture</legend>
<input name="culture" id="en-us" value="en-us" type="radio" #selected("en-us", culture) />
<label for="en-us">
English</label>
<br />
<input name="culture" id="es-es" value="es-es" type="radio" #selected("es-es", culture) />
<label for="es-es">
EspaƱol</label>
<br />
</fieldset>
}

If your culture variable equaled either "en-us" or "es-es" what you have already should work. I don't think it equals what you think it does. You could try
<input name="culture" id="testing" value="testing" type="radio" #selected("testing","testing") />
to test what you have.
That said I'd recommend using the RadioButtonFor method with a strongly typed view
public class YourViewModel
{
public string Culture { get; set; }
// Other properties
}
#model YourViewModel
#*Rest of view*#
#Html.RadioButtonFor(m => m.Culture, "en-us")
#Html.RadioButtonFor(m => m.Culture, "es-us")

Related

How to use hidden field values from view to controller in asp.net mvc 3

I have to pass hidden filed values to controller action. So I have tried in the following way, but I am getting null values.
I have tried both methods i.e formcollection and viewmodel concept
Controller
public ActionResult MapIcon()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult MapIcon(Hidden hidden)
{
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
View
#model SVGImageUpload.Models.Hidden
Razor view:#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Viewmodel
public class Hidden
{
public string hiddevalue { get; set; }
}
Try this, In Razor view:
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="submit" value="Match"/>
}
It seems to me like you are trying to get multiple values into the POST controller. In that case, and by your exam, the value from the hidden input is enough. In that case, you can setup your controller as so:
public ActionResult Index()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult Index(IEnumerable<string> hiddens)
{
foreach (var item in hiddens)
{
//do whatter with item
}
return View(new Hidden());
}
and as for your view, simple change it in order to bind to the same name "hiddens" as so:
#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" value="7" name="hiddens" />
<input type="hidden" value="2" name="hiddens" />
<input type="submit" value="Match" />
}
Hope this serves what you are looking forward to.
if your hidden value is static.Than try this
View
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Controller
[HttpPost]
public ActionResult MapIcon(Hidden hidden, string hidden1, string hidden2)
{
var hiddenvalue = hidden.hiddevalue;
var hiddenvalue1 = hidden1;
var hiddenvalue2 = hidden2;
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
Script
$(document).ready(function () {
$('#hiddevalue').val("Jaimin");
});

mvc3 checkbox value after submit

I have a form with 2 fields a dropdownlist and a checkbox. I have everything working correctly but i can not for some reason obtain the value of a checkbox if it is checked this is my code..
[HttpPost]
public ActionResult view(string pick)
{
switch (pick)
{
case "Deny":
// capture checkbox value here
break;
case "Accept":
// capture checkbox value here
break;
}
return View();
}
This is my view
#using (Html.BeginForm("view", "grouprequest", FormMethod.Post, new {}))
{
#Html.DropDownList("pick", new SelectList(new List<Object>{
new{ Text ="Accept", Value= "Accept"},new{ Text ="Deny", Value= "Deny"}}, "Value", "Text"), new {})
<input type="submit" name="work" id="work" value="Update" style="font-size:16px" />
foreach (var item in Model)
{
<input type="checkbox" id="#item.grouprequestID" name="#item.grouprequestID" value="#item.grouprequestID" />
}
}
Basically the dropdownlist has 2 options which are Accept and Deny I can capture which one the user chooses via the SWITCH-case in the controller now how can I capture the value of the checkboxes? If you notice the Checkboxes have a variable to them named #groupRequestID so every checkbox has a different unique value like 1,2,3 etc.. any help would be greatly appreciated !!
The Model
public class grouprequest
{
[Key]
public int grouprequestID { get; set; }
public int? profileID { get; set; }
public int? registrationID { get; set; }
public DateTime expires { get; set; }
public int? Grouplink { get; set; }
}
Check boxes when posted to the server act a little strange.
If a box is checked the browser will send name=value as in
<input type="checkbox" name="name" value="value" />
But if the checkbox is not checked the server doesn't send anything.
<input type="checkbox" name="Check1" id="Checks1" value="Hello" checked="checked"/>
<input type="checkbox" name="Check1" id="Checks1" value="Hello1" />
<input type="checkbox" name="Check1" id="Checks1" value="Hello2" />
Will result in Check1 = Hello
What this means is if all your check boxes are related, naming them the same will populate the same attribute of your ActionMethod. If that attribute is an enumeration it will contain only the ones that are checked.
If you have this in your view:
<input type="checkbox" name="MyValues" value="1" checked="checked"/>
<input type="checkbox" name="MyValues" value="2" />
<input type="checkbox" name="MyValues" value="3" />
and this as your controller action method:
public ActionMethod MyAction(IEumerable<int> myValues)
The myValues variable will look like this:
myValues[0] == 1
You should also note that if you are using the Html helper extension:
#Html.CheckBoxFor(m => m.MyValue)
Where MyValue is a bool the extension will create a checkbox input tag and also a hidden input tag with the same name, meaning a value will always be passed into the controller method.
Hope this helps.

Using Html.RadioButtonFor with a boolean isn't writing Checked="Checked"

I am having an issue using the RadioButtonFor helper. When the value passed in is true, it isn't displaying a "check" in either radio button. When the value is false, it works just fine.
I copied this code from the project I am working on and created a sample application and I was able to replicate the issue. If I hard coded the value to true or false it seems to work, but when I use the "!string.IsNullOrEmpty(allgroups)" it doesn't.
From the View:
<div>
#Html.RadioButtonFor(m => m.AllGroups, true) All Groups
#Html.RadioButtonFor(m => m.AllGroups, false) Current Groups
</div>
From the ViewModel:
public bool AllGroups { get; set; }
From the Controller:
public ActionResult Index(string allgroups)
{
var model = new ProgramGroupIndexViewModel
{
AllGroups = !string.IsNullOrEmpty(allgroups)
};
return View(model);
}
From view source in IE:
<div>
<input id="AllGroups" name="AllGroups" type="radio" value="True" /> All Groups
<input id="AllGroups" name="AllGroups" type="radio" value="False" /> Current Groups
</div>
From view source when value of AllGroups is false (note it works):
<div>
<input id="AllGroups" name="AllGroups" type="radio" value="True" /> All Groups
<input checked="checked" id="AllGroups" name="AllGroups" type="radio" value="False" /> Current Groups
</div>
The model binding is getting confused because you named your action parameter the same as your model property. Change the name of your Index action parameter, and it should work.
public ActionResult Index(string showAllGroups)
{
var model = new ProgramGroup
{
AllGroups = !string.IsNullOrEmpty(showAllGroups);
};
return View(model);
}
if you are returning bool from model then there is no need to check uncheck explicitly mvc will do it itself just write
<div>
#Html.RadioButtonFor(m => m.AllGroups)
#Html.RadioButtonFor(m => m.AllGroups)
</div>
however if you want to do it explicitly then
you should use following syntax to check / uncheck
Html.RadioButtonFor(m => m.AllGroups, "DisplayText", new { #checked = "checked" })
In source code you can see that it is setting true / false for value not checked attribute
in your view you can write
#if(m.AllGroups)
{
Html.RadioButtonFor(m => m.AllGroups, "DisplayText", new { #checked = "checked" })
}
else
{
Html.RadioButtonFor(m => m.AllGroups, "DisplayText" })
}

How i can submit multiple objects inside the form post values to be added

i have a create view to add answers to a question, currently the user can only add one answer at the same time when he clicks on the submit button, instead of this i want the user to be able to insert multiple answers objects into the same view and then the system to add all these new answer objects to the database after the user click on the submit button, my current view looks as the follow:-
#model Elearning.Models.Answer
#{
ViewBag.Title = "Create";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div id = "remove">
#using (Ajax.BeginForm("Create", "Answer", new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "remove"
}))
{
<div id = "returnedquestion">
#Html.ValidationSummary(true)
<fieldset>
<legend>Answer</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
</fieldset>
<input type= "hidden" name = "questionid" value = #ViewBag.questionid>
<input type= "hidden" name = "assessmentid" value = #ViewBag.assessmentid>
<input type="submit" value="Add answer" />
</div>
}
</div>
and the action methods look as the follow:-
public ActionResult Create(int questionid)//, int assessmentid)
{
ViewBag.questionid = questionid;
Answer answer = new Answer();
return PartialView("_answer",answer);
}
//
// POST: /Answer/Create
[HttpPost]
public ActionResult Create(int questionid, Answer a)
{
if (ModelState.IsValid)
{
repository.AddAnswer(a);
repository.Save();
return PartialView("_details",a);
}
return View(a);}
so how i can modify the above code to be able to insert multiple answer objects at the same view and then submit these answers objects at the same time when the user click on the submit button?
Try Post a List
Add input by javascript when user click "Add Answer".
And when submit the form ,it will post all answer data to binding to List
<script>
$(document).ready(function () {
var anwserCount = 1;
$("#addbutton").click(function () {
$("#AnwsersDiv")
.append("<input type='text' name='Anwsers[" + anwserCount + "]'/>");
anwserCount += 1;
});
});
</script>
#using (Html.BeginForm())
{
<div id="AnwsersDiv">
<input type="text" name="Anwsers[0]" />
</div>
<input id="addbutton" type="button" value="Add answer" />
<input type="submit" value="submit" />
}
Model
public class Answer
{
public List<String> Anwsers { get; set; }
}
When submit the form
I think this is what you are looking for
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Conclusion: you should make the post action with ICollection<Answer> Parameter, then it will be easy to get them when you post your main form, and create the appropriate QUESTION object, then save them all with only one submit.

ASP.Net MVC Strongly-Typed Forms

I'm having trouble understanding the difference between the following two Html.BeginForm syntax options:
#using (Html.BeginForm("SubmitSiteSearch", "Home"))
{
#Html.LabelFor(x => x.SearchText, "Quick Search:");
#Html.TextBoxFor(x => x.SearchText);
#Html.SubmitButton("btn-quick-home-search", "Search");
}
#using (Html.BeginForm<HomeController>(x => x.SubmitSiteSearch(Model), FormMethod.Post))
{
#Html.LabelFor(x => x.SearchText, "Quick Search:");
#Html.TextBoxFor(x => x.SearchText, new { id = "quick-home-search" });
#Html.SubmitButton("btn-quick-home-search", "Search");
}
[HttpPost]
public ActionResult SubmitSiteSearch(HomeViewModel model)
{
string _siteSearchText = model.SearchText;
return View(model);
}
The first form creates an instance of HomeViewModel and sets SearchText with the textbox value, while the second form does not.
Can someone explain the difference and/or how these should be used?
The difference is that the second is not part of ASP.NET MVC. You are probably using some 3rd party library such as MVC Futures assembly for example. Assuming you are using the default routes both helpers should generate the same markup:
<form action="/Home/SubmitSiteSearch" method="post">
<label for="SearchText">Quick Search:</label>
<input id="SearchText" name="SearchText" type="text" value="" />
<input id="btn-quick-home-search" name="btn-quick-home-search" type="submit" value="Search" />
</form>

Resources