this is my first post on Stackoverflow so I apologize for any errors on this post (And sorry for my English too).
I'm having a problem using C# functions on Razor. I have a form with some textboxes to fill them with data from a SQL Server database. I also have some buttons to move across the elements on the DB table (like previous, next, first...).
I'll show you the code:
#{ var codcur = "";
var descripcion = "";
var horas = "";
var tutor = "";
int pos = 0;
if(IsPost) {
pos = Convert.ToInt32(Session["position"]);
}
else {
pos = 0;
}
using(PracticaRazor2.ModeloOcupacional Contexto = new PracticaRazor2.ModeloOcupacional()) {
var registro = (from cur in Contexto.CURSOS orderby cur.COD_CUR select cur).Skip(pos).First();
codcur = registro.COD_CUR;
descripcion = registro.DESCRIPCION;
horas = registro.HORAS.ToString();
tutor = registro.TUTOR;
}
<h1>Mantenimiento cursos</h1>
<form action="~/Cursos.cshtml" method="post">
<label>Código curso:</label>
<input type="text" name="cod_cur" id="cod_cur" value="#codcur" /><br />
<label>Descripción:</label>
<input type="text" name="descripcion" id="descripcion" value="#descripcion" /><br />
<label>Horas:</label>
<input type="text" name="horas" id="horas" value="#horas" /><br />
<label>Tutor:</label>
<input type="text" name="tutor" id="tutor" value="#tutor" /><br />
<br /><br />
<input type="submit" name="first" id="first" value="|<" onclick="#first(pos)"/>
<input type="submit" name="prev" id="prev" value="<<" onclick="#prev(pos)"/>
<input type="submit" name="next" id="next" value=">>" onclick="#next(pos)"/>
<input type="submit" name="last" id="last" value=">|" />
<input type="submit" name="borra" id="borra" value="Borrar" />
<input type="submit" name="Modifica" id="mod" value="Modifica" />
<input type="submit" name="Nuevo" id="new" value="Nuevo" />
</form>
#functions{
int next(int pos) {
if(IsPost) {
pos++;
Session["position"] = pos.ToString();
}
return pos;
}
int prev(int pos) {
if(IsPost) {
pos--;
Session["position"] = pos.ToString();
}
return pos;
}
int first(int pos) {
if(IsPost) {
pos = 0;
Session["position"] = pos.ToString();
}
return pos;
}
}
}
</body>
My problem is when I click on the buttons with the onclick events, all the methods declared in "#functions" are called in reverse order, even when the page is loaded for the first time. I tried to separate them on diferent #functions, use #helper on each method instead of #functions and nothing works.
Anyone have any idea of why is this happening or knows any way to do this propely?
Thanks in advance.
Best regards.
You need to create a postback method with your controller
so lets say this is your controller you would do something like this
public ActionResult YourPageName(string NextAction)
{
if(NextAction == "next")
{
Session["position"] = (int)Session["position"] + 1;
}
elseif(NextAction == "prev")
{
Session["position"] = (int)Session["position"] - 1;
}
else
{
Session["position"] = 0;
}
return View();
}
And change your View to send the right text with your button value when its clicked on
Related
I got this structure in my ViewModel
public Dictionary<string, string> Answers { get; set; }
public List<KeyValuePair<Question, List<string>>> QuestionsAndOptions { get; set; }
public TestVM()
{
Answers = new Dictionary<string, string>();
QuestionsAndOptions = new List<KeyValuePair<Question, List<string>>>();
}
QuestionsAndOptions contains Questions and its options for my Test Page im passing to VIew.
I got different question types in my project and questions with multiple answer options is one of them.
Answers contains <string,string> pairs of question IDs and user Answer for it
I got this code in my View:
#for (int i = 0; i < Model.QuestionsAndOptions.Count; i++)
{
var question = Model.QuestionsAndOptions[i];
<tr>
<td>
<b>#question.Key.Text</b>
#if (question.Key.TypeId == 1) /*single, radiobuttons*/
{
foreach (var answer in question.Value)
{
<input type="hidden" name="testVM.Answers[#question.Key.Id].Key" value="#question.Key.Id" />
<input type="hidden" name="testVM.Answers.Index" value="#question.Key.Id" />
<input type="hidden" name="testId" value="#Model.Test.Id" />
#Html.RadioButton("testVM.Answers[" + question.Key.Id + "].Value", answer, false) #answer
}
}
#if (question.Key.TypeId == 2) /*multiple, checkboxes*/
{
foreach (var answer in question.Value)
{
<input type="hidden" name="testVM.Answers[#question.Key.Id].Key" value="#question.Key.Id" />
<input type="hidden" name="testVM.Answers.Index" value="#question.Key.Id" />
<input type="hidden" name="testId" value="#Model.Test.Id" />
#Html.CheckBox("testVM.Answers[" + question.Key.Id + "].Value", answer) #answer
}
}
#if (question.Key.TypeId == 3) /*string text, textbox*/
{
foreach (var answer in question.Value)
{
<input type="hidden" name="testVM.Answers[#question.Key.Id].Key" value="#question.Key.Id" />
<input type="hidden" name="testVM.Answers.Index" value="#question.Key.Id" />
<input type="hidden" name="testId" value="#Model.Test.Id" />
#Html.TextBox("testVM.Answers[" + question.Key.Id + "].Value")
}
}
First and third If(){...} works fine and i getting what i need after submit, but for checkboxes i'm obviously geting true/false
I want checkboxes to pass strings (checked values) to Answer dictionary
If you want to bind value to checkbox,you can try to set value in checkbox,try to use the following code:
<input type="checkbox" value=#answer name="testVM.Answers[" + question.Key.Id + "].Value" />#answer
When the checkbox is checked the value of the checkbox(#answer) will be passed to action.
I'm doing a course on PluralSight but the code in the course is not complete and there is a quickedit IActionResult that I can't seem to figure out.
In my View I have the code below:
#model IList<string>
#if (Model.Count > 0)
{
<form asp-action="QuickEdit" method="post">
#for (var i = 0; i < Model.Count; i++)
{
<div class="form-group">
<label>Soup name #(i + 1);</label>
<input id="soupNames" name="soupNames" asp-for="#Model[i]" class="form-control"/>
</div>
}
<button type="submit" class="btn btn-primary">Update</button>
</form>
}
else
{
<h2>No Soups in the system</h2>
}
The Controller:
public IActionResult QuickEdit()
{
var soupNames = _soupRepository.AllSoups.Select(s => s.SoupName).ToList();
return View(soupNames);
}
[HttpPost]
public IActionResult QuickEdit(List<string> soups)
{
var soupNames = _soupRepository.AllSoups.Select(s => s.SoupName).ToList();
for (var i = 0; i < soupNames.Count; i++)
{
soupNames[i] = soups[i];
}
return View(soups);
}
Could someone help me out?
I want the values passed through replace the original values when I click the update button.
this line
<input id="soupNames" name="soupNames" asp-for="#Model[i]" class="form-control"/>
need to change to something like
<input id="#(i)_soups" name="[#(i)].soups" asp-for="#Model[i]" class="form-control"/>
you need to google model binding lists
try , it may show you the raw syntax so you can change to just input
#Html.TextBoxFor(m => #Model[i] )
I am trying to pass a value from partial view to parent view. I tried the below which didn't worked for me. Can some one help me out how can I achieve this? By using the value that partial view returned, I am trying to hide a button which is in the parent view.
Parent View:
<div id="ProductCount">
#{
Html.RenderAction("ProductPartialView", "ProductList", new { area = "PR", ProductID = Model.ProductID, allowSelect = true});
}
<div class="saveBtnArea">
<input type="submit" value="Submit App" id="btn-submit" />
</div>
jQuery(document).ready(function () {
var ProductCount = jQuery("#ProductCount").val();
if (ProductCount == 0) {
jQuery("#btn-submit").hide();
}
else {
jQuery("#btn-submit").show();
}
});
Partial View:
<fieldset>
<div>
<input type="hidden" id="ProductCount" value="5" />
</div>
</fieldset>
You can implement change event for hidden input field like this
$('#ProductCount').change(function(){
var ProductCount = $(this).val();
if (ProductCount == 0) {
jQuery("#btn-submit").hide();
}
else {
jQuery("#btn-submit").show();
}
}).trigger('change');
$('#ProductCount').val(5);
$('#ProductCount').change(function(){
var ProductCount = $(this).val();
if (ProductCount == 0) {
jQuery("#btn-submit").hide();
}
else {
jQuery("#btn-submit").show();
}
}).trigger('change');
$('#ProductCount').val(5);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='hidden' id='ProductCount' />
<button id='btn-submit'>Submit</button>
I have a asp.net mvc application with razor engine.
In a view Home i have this snippet:
<section id="form_admin">
<form action="/Super/Manipuler" method="post">
<fieldset>
<legend>Formulaire d'ajout d'un administrateur</legend>
#Html.Label("Login")
#Html.Label("Mail")
#Html.Label("Password")
#Html.Label("Name")
<br />
<br />
#if(Model != null){
foreach (Upload.Models.AdminModels admin in Model)
{
if (i == 0){
<input type="radio" checked class="radio" name="radio" value="#admin.Login" >
}
else{
<input type="radio" class="radio" name="radio" value="#admin.Login" style="margin-left:0.3px;">
}
<label id="log">#admin.Login</label>
<label id="logm">#admin.Mail</label>
<label id="logp">#admin.Password</label>
<label id="logn">#admin.Name</label>
<br />
i++;
}
}
<br />
<input type="submit" value="Editer" name="submit_button"/>
<input type="submit" value="Supprimer" name="submit_button" />
Créer un nouveau compte
</fieldset>
</form>
</section>
In the controller : the action Manipuler is the below:
public ActionResult Manipuler()
{
string buttonName = Request.Form["submit_button"];
string _login = Request.Params["radio"];
Upload.Models.AdminModels admin = new AdminModels();
Upload.Models.CompteModels.Modifiying_login = _login;
if (buttonName == "Editer") { return RedirectToAction("Edit", "Admin"); }
else { admin.Delete_admin(_login); return RedirectToAction("Home", "Super"); }
}
It's works fine but i'd like to change the radiobox to checkbox.
My question is how to know all checked box in the collection of checkbox in the action Manipuler ?
Take a look at Phil Haack's article on model binding a checkbox list. Basically, you just need to set up the HTML in a specific way (name your checkboxes the same which will then convert the various POSTed values into a list).
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
In my aspx page i am having a checkbox list ..It has binded values from a table..
I need to validate the checkbox list ..I tried the following script
var checkBoxCount = 0;
var elements = document.getElementById('<%=ChkBoxList.ClientID%>');
for(i=0; i<elements.length;i++)
{
if(elements[i].checked)
checkBoxCount++;
}
if (checkBoxCount == 0)
{
alert("Please choose atleast one");
return false;
}
But I can't get the required output, it requires to select all the values in the checkbox list ..My need is atleast only one item must be selected from the checkbox list.. Using javascript
Thanks in advance...
function readListControl()
{
var tableBody = document.getElementById('CheckBoxList1').childNodes[0];
for (var i=0;i<tableBody.childNodes.length; i++)
{
var currentTd = tableBody.childNodes[i].childNodes[0];
var listControl = currentTd.childNodes[0];
if ( listControl.checked == true )
alert('#' + i + ': is checked');
}
}
document.getElementById returns an element, not an array.
One way to do this would be to get the container and iterate through the inputs, like so:
var container = document.getElementById('<%=ChkBoxList.ClientID%>').parentNode;
var inputs = container.getElementsByTagName('input');
for (var i=0; i<inputs.length; i++) {
if (typeof inputs[i] = "checkbox") {
// statements
}
}
You may also want to qualify the inputs with more conditional statements. This just gives you the broad brush strokes.
You will have to show us your generated html.
However, here is a working example:
<html>
<body><form name="myform" method="POST" action="" onsubmit="return validate();">
<input type="checkbox" name="mybox" value="1" /> 1
<input type="checkbox" name="mybox" value="2" /> 2
<input type="checkbox" name="mybox" value="3" /> 3
<input type="checkbox" name="mybox" value="4" /> 4
<input type="checkbox" name="mybox" value="5" /> 5
<input type="submit" value="Submit Form" />
</form>
<script type = "text/javascript">
function validate() {
var checkBoxCount = 0;
for (var i = 0; i< 5; i++) {
if(document.myform["mybox"][i].checked){
checkBoxCount ++;
}
}
if (checkBoxCount == 0) {
alert ("Tick a box!");
return false;
}
return true;
}
</script>
</body>
</html>
var k=0;
var ControlRef = document.getElementById('ChkBoxList');
var CheckBoxListArray = ControlRef.getElementsByTagName('input');
for (var i=0; i