How can i set the value of my textbox using radio button? - c#

this is my controller view
public ActionResult rb()
{
subject ts = new subject();
ts.subjectlist = db.tbSubjs.ToList();
ts.selectsubj = "";
return View(ts);
}
[HttpPost]
public ActionResult rb(subject sj, FormCollection frm)
{
if (ModelState.IsValid)
{
var selectsubj = sj.selectsubj;
string getcode = frm["subj"];
ViewBag.ssss = getcode;
}
return View("Index");
}
and this is my class
public class subject
{
public List<tbSubj> subjectlist { get; set; }
public string selectsubj { get; set; }
}
Here is my code for the radio button
<div style="text-align: left">
#using (Html.BeginForm("rb", "Home"))
{
<div>------</div>
foreach (var ts in Model.subjectlist)
{
<div>
#Html.Label(ts.SubjCode)
#Html.RadioButtonFor(m => m.subjectlist, ts.SubjCode)
</div>
}
foreach (var getsubj in Model.subjectlist)
{
<div>------------------</div>
<div>
#getsubj.SubjCode
#Html.RadioButton("subj", getsubj.SubjCode)
</div>
}
<br />
<input id="Submit" type="submit" value="Submit" />
}
</div>
and i want to set a value in my textbox in this view by getting the value of my radio button.
#model ATM.Models.subject
#{
ViewBag.Title = "rb";
}
<h2>rb</h2>
#Html.TextBox(m => m.selectsubj)
If someone is willing to help me please help me.

Assuming that your action actually looks more like the following:
[HttpPost]
public ActionResult rb(subject sj, FormCollection frm)
{
if (ModelState.IsValid)
{
var selectsubj = sj.selectsubj;
string getcode = frm["subj"];
ViewBag.ssss = getcode;
return View("view_with_textbox");
}
return View("Index");
}
You could do this:
[HttpPost]
public ActionResult rb(subject sj, FormCollection frm)
{
if (ModelState.IsValid)
{
var selectsubj = sj.selectsubj;
string getcode = frm["subj"];
var model = new ATM.Models.subject()
{
selectsubj = getcode
};
return View("view_with_textbox", model);
}
return View("Index");
}
Thereby passing the value in via the model.

Related

Call HttpPost with Ajax.BeginForm not work

I tried to call method from controller with Ajax, but it never enters the method, i'm import unobtrusive and validate in Bundle, and always refresh all the page. I'm first time in C# i use vb.net, maybe it's a basical error, but i search a lot and try diferent ways and nothing. thanks for ur time and i hope someone can help me
Update: i have a form inside Master page and that generate the problem D:
View
#model PlanificacionOperacional.Models.FiltroView
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Styles
{
#Styles.Render("https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css")
#Styles.Render("https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css")
}
<div class="card-header header-elements-inline" style="padding-top:0;"><h4 class="card-title">Muestreos</h4></div>
<fieldset>
#using (Ajax.BeginForm("Filtrar", "Muestreo",
new AjaxOptions
{
UpdateTargetId = "tabless",
HttpMethod = "POST"
}))
{
<div class="form-group">
#Html.DropDownListFor(model => model.predio, new SelectList(ViewBag.formularios, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Predio" })
#Html.DropDownListFor(model => model.zona, new SelectList(ViewBag.zonas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Zona" })
#Html.DropDownListFor(model => model.area, new SelectList(ViewBag.areas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Area" })
</div>
<div class="form-group" style="align-self:center;">
#*<input type="submit" value="Filtrar" class="btn btn-primary" style="width:150px;" />*#
<button type="submit">Filtrar</button>
</div>
}
</fieldset>
<div id="tabless" class="card-body" style="">
<table id="table_id" class="display">
<thead>
<tr>
<th></th>
<th>ID Muestro</th>
<th>Area</th>
<th>Id Predio</th>
<th>Predio</th>
<th>Formulario</th>
<th>APLA</th>
<th>Total Parcelas</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.muestreos)
{
<tr>
<td><input type="checkbox" id="cbox2" value="second_checkbox"></td>
<td>#item.IdMuestreo</td>
<td>#item.Area</td>
<td>#item.IdPredio</td>
<td>#item.NomPredio</td>
<td>#item.Formulario</td>
<td>#item.APLA</td>
<td>#item.TotalParcela</td>
</tr>
}
</tbody>
</table>
</div>
#section JavaScriptToFooter {
#Scripts.Render("https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js")
#Scripts.Render("https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js")
<script>
$(document).ready(function () {
$('#table_id').DataTable();
$('.selectpicker').selectpicker();
});
</script>
#Scripts.Render("~/bundles/jqueryval")
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PlanificacionOperacional.Models;
using PlanificacionOperacional.Repository;
namespace PlanificacionOperacional.Controllers
{
public class MuestreoController : Controller
{
// GET: Muestreo
public ActionResult Index()
{
MuestreoRepository muestreo = new MuestreoRepository();
List<Muestreo> muestreos = muestreo.TraeMuestreo();
List<Filtro> predios = muestreo.TraePredios();
List<Filtro> zonas = muestreo.TraeZonas();
List<Filtro> areas = muestreo.TraeAreas();
ViewBag.muestreos = muestreos;
ViewBag.formularios = predios;
ViewBag.zonas = zonas;
ViewBag.areas = areas;
return View();
}
[HttpPost]
public ActionResult Filtrar(FiltroView model)
{
int predio = Convert.ToInt32(Request["predio"].ToString());
int zona = Convert.ToInt32(Request["zona"].ToString());
return View();
}
// GET: Muestreo/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Muestreo/Create
public ActionResult Create()
{
return View();
}
// POST: Muestreo/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Muestreo/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Muestreo/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Muestreo/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Muestreo/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PlanificacionOperacional.Models
{
public class FiltroView
{
public int zona { get; set; }
public long predio { get; set; }
public int area { get; set; }
}
}
You are using MVC but you dont have any model. You will never be able to submit form without model. So for the start create a model
public ViewModel
{
public int ZonaId {get; set;]
public int AreaId {get;set;}
.... and so on
}
and after this view
#model ViewModel
......
#Html.DropDownListFor(model=>model.PredioId, new SelectList(ViewBag.formularios, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Predio" })
#Html.DropDownListFor(model=>model.ZonaId, new SelectList(ViewBag.zonas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Zona" })
#Html.DropDownListFor(model=>model.AreaId, new SelectList(ViewBag.areas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Area" })
.... and so on
action
public ActionResult Filtrar(ViewModel model)
{
int predioId = model.PredioId;
int zonaId = model.ZonaId;
.... your code
}
PS.
Get rid of all your viewbags. It looks very unprofessionaly and it is hard to mantain this kind of code. Include everything in the ViewModel.
public ActionResult Index()
{
MuestreoRepository muestreo = new MuestreoRepository();
var model=new ViewModel{
muestreos = muestreo.TraeMuestreo(),
predios = muestreo.TraePredios();
zonas = muestreo.TraeZonas();
areas = muestreo.TraeAreas();
....and so on
}
return View(model);
}

I'm using a hidden for with a checkbox to send strings to a property, but they are sent even if the checkbox isn't checked

so I've been trying to use a checkbox to send a list of values to a string property in my model.
but for some reason, the values are sent, even after i initialized with the bool false and left the checkbox unchecked.
these are my models
public class Profesor
{
public List<AsignaturaModelo> Asignaturas { get; set; }
public Profesor()
{
Asignaturas = new List<AsignaturaModelo>();
}
}
public class AsignaturaModelo
{
public string NombreA { get; set; }
public bool Selected { get; set; }
}
My controller
public ActionResult Create()
{
var model = new Profesor
{
Asignaturas = new[]
{
new AsignaturaModelo{NombreA = "Programacion 1", Selected = false},
new AsignaturaModelo {NombreA = "Programacion 2", Selected = false}
}.ToList()
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Profesor modelo)
{
try
{
if (ModelState.IsValid)
{
profesors.Add(modelo);
return RedirectToAction(nameof(Index));
}
}
catch
{
return View(modelo);
}
return View(modelo);
}
My view
#Html.EditorFor(x => x.Asignaturas)
and my EditorTemplate
#model AsignaturaModelo
<div>
#Html.CheckBoxFor(x => x.Selected)
#Html.HiddenFor(x => x.NombreA)
#Html.LabelFor(x => x.Selected, Model.NombreA)
</div>
Not sure what am i doing wrong, also sorry for the variable names. Thanks in advance!
Do you mean in the propertyProfesor modelo of post method,you only want selected item to pass their NombreA?If so,here is a demo worked.
View:
#model Profesor
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<form method="post" onsubmit="return check()">
#Html.EditorFor(x => x.Asignaturas, "EditorTemplate")
<div>
<input type="submit" beforesubmit="" value="submit" />
</div>
</form>
#section scripts{
<script type="text/javascript">
function check() {
var count = 0;
$('input[type="checkbox"]').each(function () {
var id = "#" + $(this).prop("id").replace("Selected", "NombreA");
var name = $(this).prop("name").replace("Selected", "NombreA");
var tempname = name.replace(/[0-9]/, "number").replace(/0-9/ig, "");
$('input[name="' + name.replace("NombreA", "Selected") + '"][type="hidden"]').attr("name", name.replace("NombreA", "Selected") + "_unselected");
if ($(this).prop("checked")) {
var newName = tempname.replace("number", ""+count);
$(id).attr("name", newName);
$(this).attr("name", newName.replace("NombreA", "Selected"));
count++;
} else {
$(id).attr("name", name + "_unselected");
}
})
return true;
}
</script>
}
EditorTemplate:
#model List<AsignaturaModelo>
#for (int i=0;i<Model.Count();i++)
{
<div>
#Html.CheckBoxFor(x => x[i].Selected)
#Html.HiddenFor(x => x[i].NombreA)
#Html.LabelFor(x => x[i].Selected, Model[i].NombreA)
</div>
}
Result:

Retrieving ViewModel with multiple list objects once its posted

I have a viewmodel class like this:
public class ViewModel
{
public string VendorService { get; set; }
public List<ResponseView> responseList { get; set; }
}
Controller has get and post edit actions:
public ActionResult Edit(int? id)
{
List<ResponseView> resp = getResponseView(id); //get the list of ResponseView objects.
ViewModel view = new ViewModel();
view.responseList = resp;
view.VendorService = "Car Manufacturer";
return View(view);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel view)
{
if (ModelState.IsValid)
{
List<ResponseView> respList = new List<ResponseView>();
respList = view.responseList;
foreach(ResponseView resp in respList)
{
Debug.WriteLine(resp.Question);
}
return RedirectToAction("editConfirm");
}
return View("Index");
}
Edit.cshtml
#model Tools.Models.ViewModel
#{
List<Tools.Models.ResponseView> respList= Model.responseList as List<Tools.Models.ResponseView;
}
#foreach (var item in respList)
{
<div class="col-md-5">
#Html.EditorFor(model => item.Response, "" } })
#Html.ValidationMessageFor(model => item.Response, "", "" })
</div>
}
I am able to display the view and all the data in the View Model as required. But I am getting a null pointer reference when I try to retrieve the response in my post action, on foreach line below.
List<ResponseView> respList = new List<ResponseView>();
respList = view.responseList;
foreach(ResponseView resp in respList)
{
Debug.WriteLine(resp.Response);
}
You have to use for instead foreach . Please try this,
#for (int i = 0; i < Model.responseList.Count; ++i) {
<div>
#Html.EditorFor(model => Model.responseList[i].Response, "")
</div>

Post Dropdown values/keys using FormCollection

I have a form that posts to an action:
public ActionResult Index()
{
CheckDataVM vm = new CheckDataVM();
vm.SerialNumbers = GetAllSerials();
vm.CustomerNames = GetAllCustomers();
vm.DateFrom = DateTime.Now.AddDays(-1);
vm.DateTo = DateTime.Now;
return View(vm);
}
[HttpPost]
public ActionResult Index(CheckDataVM v)
{
CheckDataVM vm = new CheckDataVM();
vm.SerialNumbers = GetAllSerials();
var s = vm.SerialNumbers.First().Text.ToString();
vm.Channels = GetAllChannels(s);
vm.DateFrom = DateTime.Now.AddDays(-1);
vm.DateTo = DateTime.Now;
return View(vm);
}
In my Razor view, I have post:
#using (Html.BeginForm("Index", "CheckData", FormMethod.Post, new { id = "SerialsForm" }))
{
<div class="card-body" style="font-size: small;">
<div class="form-group">
#Html.DropDownListFor(x => x.SelectedSerial, Model.SerialNumbers, new { #class = "form-control form-control-sm" })
<input type="submit" value="Submit" />
</div>
</div>
}
The view model is:
public class CheckDataVM
{
public string CustomersName { get; set; }
public string SelectedSerial { get;set; }
[Display(Name="Select a serial number")]
public IEnumerable<SelectListItem> SerialNumbers { get; set; }
}
The dropdowns work, but when I submit the form the only thing I get back is the object name (SerialNumbers) as the key.
I want to be able to get the selected item from the dropdown list and pass this to the FormCollection in the Httpost of the Index action. For the life of me, I cannot get it to work!
I am expecting to see a key called 'CustomersDdl' and it's value. For example, if I had a dropdown full of countries and I pick England, I am expecting to see a value come back in the FormCollection saying England.
What am I doing wrong?
The value to postback is depending on how you create "SelectListItem", in your case it is in the method "GetAllSerials()"
vm.SerialNumbers = serialNumbers.Select(serial => new SelectListItem
{
Selected = serial.id == vm.SelectedSerial ? true : false,
Text = serial.Name,
Value = serial.Name
}).ToList();

Using partial view updates asp.net ajax

Trying to display only one comment from the text box in the partial view.
To get some data you need the Session Controller:
private ConferenceContext context = new ConferenceContext();
//
// GET: /Session/
public ActionResult Index()
{
ConferenceContext context = new ConferenceContext();
List<Session> sessions = context.Sessions.ToList();
return View(sessions);
}
//
// GET: /Session/Details/5
public ActionResult Details(int id = 0)
{
Session session = context.Sessions.Find(id);
if (session == null)
{
return HttpNotFound();
}
return View(session);
}
Details View in the Session Folder:
#model Conference.Models.Session
<h3>
#Model.Title
</h3>
<div>
#Model.Abstract
</div>
#Html.Action("_GetForSession", "Comment", new { SessionID = Model.SessionID })
Then the CommentController, which is using the partial view _GetForSession to display the text from the Text Box:
ConferenceContext context = new ConferenceContext();
public PartialViewResult _GetForSession(Int32 sessionID)
{
ViewBag.SessionID = sessionID;
List<Comment> comments = context.Comments.Where(c => c.SessionID == sessionID).ToList();
return PartialView("_GetForSession", comments);
}
[ChildActionOnly()]
public PartialViewResult _CommentForm(Int32 sessionID)
{
Comment comment = new Comment() { SessionID = sessionID };
return PartialView("_CommentForm", comment);
}
[ValidateAntiForgeryToken()]
public PartialViewResult _Submit(Comment comment)
{
context.Comments.Add(comment);
context.SaveChanges();
List<Comment> comments = context.Comments.Where(c => c.SessionID == comment.SessionID).ToList();
ViewBag.SessionID = comment.SessionID;
return PartialView("_GetForSession", comments);
}
Here is the _GetForSession View from the Comment folder:
#model IEnumerable<Conference.Models.Comment>
<div id="comments">
<ul>
#foreach (var comment in Model)
{
<li>#comment.Content</li>
}
</ul>
#using(Ajax.BeginForm("_Submit", "Comment", new AjaxOptions() { UpdateTargetId = "comments" }))
{
#Html.AntiForgeryToken();
#Html.Action("_CommentForm", new { SessionID = ViewBag.SessionID })
}
</div>
The _GetForSession gets its data from the _CommentForm in the Comment folder:
#model Conference.Models.Comment
#Html.HiddenFor(m => m.SessionID)
<div>
#Html.LabelFor(m => m.Content)
#Html.EditorFor(m => m.Content)
</div>
<button type="submit">Submit Comment</button>
Now the main Context would be coming from ConferenceContext in the Models:
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Speaker> Speakers { get; set; }
public DbSet<Comment> Comments { get; set; }
}
And the Context itself from the ConferenceContextInitializer:
public class ConferenceContextInitializer : DropCreateDatabaseAlways<ConferenceContext>
{
protected override void Seed(ConferenceContext context)
{
context.Sessions.Add(
new Session()
{
Title = "Partial View",
Abstract = "View Within the Main",
Speaker = context.Speakers.Add(new Speaker()
{
Name = "John Smith",
EmailAddress = "johnsmith#nowhere.com"
})
});
context.SaveChanges();
}
}
So, my question is can it be possible to display only one comment in the partial view not two?

Categories

Resources