How get values into a select box from sql server - asp.net-mvc

Can anyone help me to populate a select box with values from sql server. I'm using MVC ASP.NET, I have a form, that is from a table X, one of it columns it's called Location and brings the city where it's from, but i have all the cities in another table Y, and want to insert the select inside that form. How should i enter the code inside the model/controller.
Here is how i set the form for table X:
Model:
public int Insertar(Inmueble inmueble)
{
SqlConnection conexion = new SqlConnection("Data Source=USUARIO-PC\\SQLEXPRESS;Integrated Security=True;Initial Catalog=jaera;");
conexion.Open();
SqlCommand comando = conexion.CreateCommand();
comando.CommandText = "insert into Inmuebles (Titulo, Descripcion, Ambientes, Precio, Localidad, Tags, Usuario)" +
"output inserted.Id values (#Titulo, #Descripcion, #Ambientes, #Precio, #Localidad, #Tags, #Usuario)";
comando.Parameters.AddWithValue("#Titulo", inmueble.Titulo);
comando.Parameters.AddWithValue("#Descripcion", inmueble.Descripcion);
comando.Parameters.AddWithValue("#Ambientes", inmueble.Ambientes);
comando.Parameters.AddWithValue("#Precio", inmueble.Precio);
comando.Parameters.AddWithValue("#Localidad", inmueble.Localidad);
comando.Parameters.AddWithValue("#Tags", inmueble.Tags);
comando.Parameters.AddWithValue("#Usuario", inmueble.Usuario);
int nuevoId = (int)comando.ExecuteScalar();
inmueble.Id = nuevoId;
conexion.Close();
return nuevoId;
}
This is my controller:
[HttpPost]
public ActionResult Create(FormCollection formulario)
{
string Titulo = formulario["Titulo"];
string Descripcion = formulario["Descripcion"];
int Precio = Convert.ToInt32(formulario["Precio"]);
int Ambientes = Convert.ToInt32(formulario["Ambientes"]);
int Localidad = Convert.ToInt32(formulario["Localidad"]);
string Usuario = formulario["Usuario"];
string Tags = formulario["Tags"];
Inmueble inmueble = new Inmueble();
inmueble.Titulo = Titulo;
inmueble.Localidad = Localidad;
inmueble.Precio = Precio;
inmueble.Ambientes = Ambientes;
inmueble.Usuario = Usuario;
inmueble.Descripcion = Descripcion;
inmueble.Tags = Tags;
InmueblesManager managerInmuebles = new InmueblesManager();
int idInsertado = managerInmuebles.Insertar(inmueble);
if (Request.Files.Count > 0 &&
Request.Files[0].ContentLength > 0) //para validar que vino el archivo
{
string rutaFinal = Server.MapPath("~/Content/imagenes/inmuebles/" + idInsertado + ".jpg");
Request.Files[0].SaveAs(rutaFinal);
}
return RedirectToAction("Index", "Home");
}
And this is how it looks at html code the form:
<form action="#Url.Action("Create", "Inmuebles")" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="Titulo">Titulo</label>
<input id="Titulo" name="Titulo" type="text" placeholder="Titulo" />
</div>
<div class="form-group">
<label for="Localidad">Localidad</label>
<input id="Localidad" name="Localidad" type="text" placeholder="Localidad del Inmueble" />
</div>
<div class="form-group">
<label for="Descripcion">Descripcion</label>
<textarea id="Descripcion" name="Descripcion" placeholder="Ingresa aqui la descripcion"></textarea>
</div>
<div class="form-group">
<label for="Precio">Precio</label>
<input type="number" id="Precio" name="Precio" />
</div>
<div class="form-group">
<label for="Ambientes">Ambientes</label>
<input type="number" id="Ambientes" name="Ambientes" />
</div>
<div class="form-group">
<label for="Tags">Tags</label>
<input id="Tags" name="Tags" type="text" placeholder="Tags para una busqueda mas rapida" />
</div>
<div>
<input type="hidden" value="#(((ja_era.Models.Usuario)Session["usuario"]).NombreDeUsuario)" name="Usuario" />
</div>
<div class="form-group">
<label for="imagen">Imagen</label>
<input id="imagen" name="imagen" type="file" />
</div>
<input type="submit" value="Guardar" />

You haven't even attempted anything, which is kind of a no-no around these parts. I will give you a bit of general guidance, though. First, use a view model to pass data to/from the view. You should pretty much never take a FormCollection.
public class InmuebleViewModel
{
public string Titulo { get; set; }
public int Localidad { get; set; }
public int Precio { get; set; }
public int Ambientes { get; set; }
public string Usuario { get; set; }
public string Descripcion { get; set; }
public string Tags { get; set; }
}
Then, your get action should pass this to your view:
public ActionResult Create()
{
var model = new InmuebleViewModel();
return View(model);
}
Your view should use this model and utilize the HTML helpers to generate your inputs:
#model Namespace.To.InmuebleViewModel
...
<div class="form-group">
#Html.LabelFor(m => m.Titulo)
#Html.EditorFor(m => m.Titulo, new { htmlAttributes = new { placeholder = "Titulo" } })
</div>
...
Finally, your post action should take this view model as a param:
[HttpPost]
public ActionResult Create(InmuebleViewModel model)
{
...
}
That's all just standard MVC best practice stuff. However, using the view model also gives you the ability to have a select list on it:
public IEnumerable<SelectListItem> FooOptions { get; set; }
Which you can then use in your view:
#Html.DropDownListFor(m => m.Foo, Model.FooOptions)
You just need to populate that property in both your get and post actions. For that, I recommend adding a protected method to your controller that both can call to keep it dry:
protected void PopulateFooOptions(InmeubleViewModel model)
{
// retrieve you options from the database, selected into an enumerable of `SelectListItem`
model.FooOptions = options;
}
Then, both your get and post Create actions call this before returning the view:
PopulateFooOptions(model);
return View(model);

Related

EF Core ModelSate Invalid because form is passing foreign key name and value attributes

Very new to MVC Core and C# and just as I think I'm getting the hang of something there's a new curve ball. I have a form which is based on a model which has a foreign key. When I submit the form to the controller the modelState is invalid because the form is passing something back which isn't in the model it is based on. Here is the model:
public partial class Agreement
{
public Agreement()
{
AgreementAmendments = new HashSet<AgreementAmendment>();
Bundles = new HashSet<Bundle>();
Invoices = new HashSet<Invoice>();
}
public int Id { get; set; }
public int OrgId { get; set; }
public string AgreementNumber { get; set; } = null!;
public string? IrespondReference { get; set; }
public string? DocumentLink { get; set; }
public virtual Organization Org { get; set; }
public virtual ICollection<AgreementAmendment> AgreementAmendments { get; set; }
public virtual ICollection<Bundle> Bundles { get; set; }
public virtual ICollection<Invoice> Invoices { get; set; }
}
This is the Get Create Action Method:
public IActionResult Create()
{
ViewData["OrgId"] = new SelectList(_context.Organizations, "Id", "ShortName");
return View();
}
This is the form:
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrgId" class="control-label">Organization</label>
<select asp-for="OrgId" class ="form-control" asp-items="ViewBag.OrgId"></select>
</div>
<div class="form-group">
<label asp-for="AgreementNumber" class="control-label">Agreement Number</label>
<input asp-for="AgreementNumber" class="form-control" />
<span asp-validation-for="AgreementNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="IrespondReference" class="control-label">Internal Reference</label>
<input asp-for="IrespondReference" class="form-control" />
<span asp-validation-for="IrespondReference" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DocumentLink" class="control-label">Document Link</label>
<input asp-for="DocumentLink" class="form-control" />
<span asp-validation-for="DocumentLink" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
And this is the HttpPost Create Action Method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("OrgId,AgreementNumber,IrespondReference,DocumentLink")] Agreement agreement)
{
if (ModelState.IsValid)
{
_context.Add(agreement);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["OrgId"] = new SelectList(_context.Organizations, "Id", "Id", agreement.OrgId);
return View();
}
When I look at the results of the ModelState it shows an error with the Org Key but as far as I can see the form should just be returning the OrgId as per the model. Can someone please let me know where I am going wrong.
Created a View Model for Agreements to handle the form input and then passed that to the base Agreement Model which seems like unnecessary work. Why can't EF Core handle this stuff without having to constantly build View Models just because there is a foreign key?
Anyway, this is the final HttpPost code for others who run into the same issue:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(AgreementWriteViewModel newagreement)
{
if (ModelState.IsValid)
{
var model = new Agreement
{
OrgId = newagreement.OrgId,
AgreementNumber = newagreement.AgreementNumber,
IrespondReference = newagreement.IrespondReference,
DocumentLink = newagreement.DocumentLink,
};
_context.Add(model);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["OrgId"] = new SelectList(_context.Organizations, "Id", "ShortName", newagreement.OrgId);
return View();
}

how can i assign value to textbox in MVC - Sharepoint Provider-hosted

I want to get and assign value to my textbox from controller.
here is my textbox:
<input type="text" class="form-control" id="RegardingTo" name="RegardingTo" value="??????"/>
then i want to get the value from this action.
public ActionResult Edit(int? RequestID)
{
if (RequestID <= 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var ReqID = db.usp_RequestGetDetails(RequestID);
if (ReqID == null)
{
return HttpNotFound();
}
return View();
}
please help :)
Yes you can assign value to the textbox using Model, First of all create a model then link that model with your view. And In Controller assign the value to model and return to the view.
Or At runtime if you want to assign the value to your text box then you can use Ajax call to your controller and get the value.
Please revert in case of any query.
See what i am doing to do the same, Make a custom model with your relevant fields, then assign values to them in controller, and pass this values to View, And that's it. :)
Custom Model
public partial class QuoteParameter
{
public Nullable<System.DateTime> TripStartDateLimit { get; set; }
public Nullable<System.DateTime> TripEndDateLimit { get; set; }
public int PolicyId { get; set; }
}
Controller
public ActionResult Index()
{
QuoteParameter quote = new QuoteParameter();
quote.TripEndDateLimit = DateTime.Now;
quote.TripEndDateLimit = DateTime.Now;
quote.PolicyId = 5;
return View(quote);
}
View
#model EHIC.Models.Models.QuoteParameter
By Razor syntax
<div class="row-fluid span12">
<div class="span4">
<p><strong>Trip Start Date Limit :</strong></p>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.TripStartDateLimit, "{0:dd/MM/yyyy}", new { #class = "form-control", #placeholder = "Policy StartDate Limit", #required = true })
</div>
</div>
<div class="row-fluid span12">
<div class="span4">
<p><strong>Trip End Date Limit :</strong></p>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.TripEndDateLimit, "{0:dd/MM/yyyy}", new { #class = "form-control", #placeholder = "Policy EndDate Limit", #required = true })
</div>
</div>
By HTML Code
<input type="text" class="form-control" id="TripStartDateLimit" name="TripStartDateLimit" value="#Model.TripStartDateLimit"/>
<input type="text" class="form-control" id="TripEndDateLimit" name="TripEndDateLimit" value="#Model.TripEndDateLimit"/>
EDIT
By Click on this button you can send the PolicyId(as an example) to controller, and then you can do whatever you want there..!!!
<a href='../../controller/Edit?PolicyId=#Models.PolicyId'>
<span title='Edit'></span>
</a>
#Html.ActionLink("Edit","Edit", new { id = item.RequestID })
You can find the PolicyId which you sent from the Edit Page..
public ActionResult Edit(int id)
{
//Get your data from Store_procedure..
return View();
}

Input type checkbox with MVC razor

Why is the value of my checkbox not passed to my ViewModel?
My View (I omitted input tags not relevant for this post):
#model Pro.WebUI.ViewModels.UserViewModel
#using (Html.BeginForm("ManageUsers", "Administration", FormMethod.Post,
new { id = "request-form", #class = "form-horizontal" }))
{
<div class="form-group">
<label for="inputAuthorize" class="col-lg-2 control-label">Authorize</label>
<div class="col-lg-8">
<input type="checkbox" id="Authorized" name="Authorized" value="#Model.Authorized" />
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<br /><br />
<button type="submit" class="btn btn-primary">Submit Request</button>
</div>
</div>
}
My ViewModel:
public class UserViewModel
{
[Key]
public string UserID { get; private set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Authorized { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Notes { get; set; }
}
My Controller:
[HttpPost]
public ActionResult ManageUsers(UserViewModel model)
{
if (ModelState.IsValid)
{
ProcurementUser obj = new ProcurementUser();
obj.UserName = model.Email;
obj.FirstName = model.FirstName;
obj.LastName = model.LastName;
obj.Email = model.Email;
obj.Phone = model.Phone;
obj.Authorized = model.Authorized;
UserRepository.SaveUser(obj);
//success message
}
return View(model);
}
I did not include all input tags but when I step through the code without the checkbox, all values are passed. I looked at other checkbox questions on SOF but they mostly use the #Html.Checkbox or #Html.CheckboxFor. I would like to just use input type="checkbox"
If we need to use <input> filed instead of #Html.CheckboxFor, we can use "checked=\"checked\"" syntax as in this code:
<input type="checkbox" id="Authorized" name="Authorized" value="true" #(Model.Authorized ? "checked=\"checked\"" : "") />
As has been hinted at in the comments the issue you're having is that you're not really creating your checkbox correctly:
Assuming your model has Authorized = true your mark-up would be:
<input type="checkbox" id="Authorized" name="Authorized" value="true" />
Similarly the false state would result in:
<input type="checkbox" id="Authorized" name="Authorized" value="false" />
But these aren't "checked" checkboxes - they're still "unchecked", and need the checked attribute setting:
<input type="checkbox" id="Authorized" name="Authorized" value="true" checked />
As Stephen points out - an unchecked checkbox will not send any data back to the server so that you don't get confused about which options where selected.
Finally, as has also been noted, your <label> element is for an non-existent field looking for inputAuthorize instead of Authorized.
All of these issues would be taken care of for you if you were to use the #Html.CheckboxFor and #Html.LabelFor helper classes.

mvc getting and sending data from dropdown and datetimepicker

hello everyone I have a question. I have a form which consist of dropdown textbox and datetimepicker. I can fill my dropdown from my model but I cannot post the data to the database. Here are my codes
My Controller codes this is where the data selected and shown in view
public ActionResult orderProduct()
{
Repository<OrderProduct> _ro = new Repository<OrderProduct>();
IEnumerable<OrderProduct> _orderProduct = _ro.All().OrderByDescending(o => o.id);
return View(_orderProduct);
}
I am filling the dropdownlist from database
public ActionResult addOrderProduct()
{
/*
Repository<Workshop> _rw = new Repository<Workshop>();
IEnumerable<Workshop> _workshop = _rw.All().OrderByDescending(o => o.id);
IEnumerable<SelectListItem> _selectList = from w in _workshop
select new SelectListItem {
Text = w.name,
Value = w.id.ToString()
};
*/
Repository<Workshop> _rw = new Repository<Workshop>();
IEnumerable<SelectListItem> _workshopSelectListItem = _rw.All().AsEnumerable().Select(s =>
new SelectListItem {
Text = s.name, Value=s.id.ToString()
});
ViewData["dropdown"] = _workshopSelectListItem;
return View();
}
here I am trying to post my data to the database. I cannot select data from dropdown and datetimepicker also I cannot post this data by writing manually.
public ActionResult orderProductAdd(int adet, float cmt)
{
Repository<OrderProduct> _rp = new Repository<OrderProduct>();
OrderProduct _orderProduct = new OrderProduct { workshopId = 1, orderId = 1, value = adet, shipDate = new DateTime(2005, 02, 01), cmt = cmt };
return RedirectToAction("orderProduct");
}
this is my model
[Table("OrderProduct")]
public class OrderProduct
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public int orderId { get; set; }
[ForeignKey("orderId")]
public virtual Order order { get; set; }
public int workshopId { get; set; }
[ForeignKey("workshopId")]
public virtual Workshop workshop { get; set; }
public int value { get; set; }
public float cmt { get; set; }
public DateTime shipDate { get; set; }
/*
[id]
,[orderId]
,[workshopId]
,[value]
,[cmt]
,[shipDate]
*/
}
and also this is my view "addOrderProduct"
<form action="/Order/orderProductAdd" class="form-horizontal">
<div class="control-group">
<label class="control-label">Atölye Seçiniz</label>
<div class="controls">
#Html.DropDownList("dropdown",(IEnumerable<SelectListItem>)ViewData["dropdown"],"secim yapınız", new { #class = "span6 chosen" })
#*<select class="span6 chosen" data-placeholder="Choose a Category" tabindex="1">
<option value=""></option>
<option value="Category 1">A1</option>
<option value="Category 2">A2</option>
<option value="Category 3">A3</option>
<option value="Category 4">A4</option>
</select>*#
</div>
</div>
<div class="control-group">
<label class="control-label">Adet Giriniz</label>
<div class="controls">
<input type="text" class="span6 " name="adet" />
<span class="help-inline">Sadece sayı giriniz</span>
</div>
</div>
<div class="control-group last">
<label class="control-label">İhracat Tarihi</label>
<div class="controls">
<div id="ui_date_picker_inline"></div>
</div>
</div>
<div class="control-group">
<label class="control-label">Cmt</label>
<div class="controls">
<input type="text" class="span6 " name="cmt" />
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Onayla</button>
#*<button type="button" class="btn">Cancel</button>*#
</div>
</form>
How can I solve this ? Thank you.
The first argument in the DDL (below) is the assigned parameter being passed back to the server. When you call the action you're not passing the parameter dropdown. You're only calling int adet, float cmt but not a parameter called dropdown
#Html.DropDownList("dropdown",(IEnumerable<SelectListItem>)ViewData["dropdown"],
"secim yapınız", new { #class = "span6 chosen" })
So update your code to something like the one below:
public ActionResult orderProductAdd(int adet, float cmt, string dropdown){
// DO SOMETHING HERE
}
I can't see the input control which is being constructed for the DATETIME part of your query, however it will be similar to the above. Ensure the name of the INPUT matches the parameters being passed back to the server.

Passing values of checkboxes from View to Controller

I have a view with a number of checkboxes in it. I want to be able to pass the values of the checkboxes to the controller, then output a list of the OfficeNames that have been ticked. I am not sure how to pass the values of multiple checkboxes back to the controller, or how to output the OfficeNames based on which boxes have been ticked
View:
<p>
#using (Html.BeginForm())
{
<p>
Start Date: #Html.TextBox("StartDate") <br />
<br />
End Date: #Html.TextBox("EndDate") <br />
<br />
<input type="submit" value="Filter" />
</p>
}
<p>
#foreach (var item in Model.BettingOffices)
{
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="selectedShops" value="#item.OfficeName">
}
</p>
Controller:
public class DailyReportController : Controller
{
private RiskEntities _db = new RiskEntities();
// GET: /DailyReport/
public ActionResult Index(DateTime? startDate, DateTime? endDate)
{
if (startDate == null || endDate == null)
{
var dailyReportModelBlank = new DailyReportModel();
dailyReportModelBlank.BettingOffices = (from bo in _db.BettingOffices orderby bo.OfficeName select bo ).ToList();
//dailyReportModelBlank.DailyReports.Add(new DailyReport());
return View(dailyReportModelBlank);
}
var endDateToUse = (DateTime) endDate;
endDateToUse = endDateToUse.AddDays(+1);
var dailyReportModel = new DailyReportModel
{
DailyReports = (from dr in _db.DailyReports
where dr.DailyReportDate >= startDate
&& dr.DailyReportDate <= endDateToUse
select dr).ToList(),
BettingOffices = (from bo in _db.BettingOffices select bo).ToList()
};
return View(dailyReportModel);
}
Model:
public class DailyReportModel
{
private List<DailyReport> _dailyReports = new List<DailyReport>();
private List<BettingOffice> _bettingOffices = new List<BettingOffice>();
public List<DailyReport> DailyReports
{
get { return _dailyReports; }
set { _dailyReports = value; }
}
public List<BettingOffice> BettingOffices
{
get { return _bettingOffices; }
set { _bettingOffices = value; }
}
}
BettingOffice Class:
public partial class BettingOffice
{
public int BettingOfficeID { get; set; }
public string OfficeName { get; set; }
public string OfficeCode { get; set; }
public string IpAddress { get; set; }
public Nullable<bool> SupportOnly { get; set; }
public Nullable<int> SisSrNumer { get; set; }
public Nullable<bool> Local { get; set; }
public string Server { get; set; }
}
try this :
<p>
#using (Html.BeginForm())
{
<p>
Start Date: #Html.TextBox("StartDate")
<br />
<br />
End Date: #Html.TextBox("EndDate")
<br />
<br />
<input type="submit" value="Filter" />
</p>
}
</p>
<p>
#foreach (var item in Model.BettingOffices)
{
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="bettingOfficeIDs" value="#item.BettingOfficeID">
}
</p>
And in your Action you can get the selected office ids in bettingOfficeIDs variable:
public ActionResult YourActionName(int[] bettingOfficeIDs)
Few things that need to change here.
If you want values to be passed to action method they need to be within form not outside
For MVT to 'understand' checkbox values as array (or more complex object) you need to work with their html name attribute.
I will do demonstration application below that should help you understand how it works:
CsHtml: Notice that you need to add value attribute to checkboxes to be able to read their values, checkbox gets true only when checkbox is ticked and value is true, hence the javascript. You can add as many of complex object properties as hidden fields as long as you give them names that match to the object property names in viewModel. In this case I am only passing BettingOfficeID
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).on("click", "[type='checkbox']", function(e) {
if (this.checked) {
$(this).attr("value", "true");
} else {
$(this).attr("value","false");}
});
<p>
#using (Html.BeginForm())
{
<p>
Start Date: #Html.TextBox("StartDate") <br />
<br />
End Date: #Html.TextBox("EndDate") <br />
<br />
</p>
<p>
<input type="checkbox" name="BettingOffices[0].Selected" value="true">
<input type="hidden" name="BettingOffices[0].BettingOfficeID" value="1">
<input type="checkbox" name="BettingOffices[1].Selected" value="false">
<input type="hidden" name="BettingOffices[1].BettingOfficeID" value="2">
<input type="checkbox" name="BettingOffices[2].Selected" value="true">
<input type="hidden" name="BettingOffices[2].BettingOfficeID" value="3">
<input type="checkbox" name="BettingOffices[3].Selected" value="false">
<input type="hidden" name="BettingOffices[3].BettingOfficeID" value="4">
<input type="checkbox" name="BettingOffices[4].Selected" value="true">
<input type="hidden" name="BettingOffices[4].BettingOfficeID" value="5">
</p>
<input type="submit" value="submit"/>
}
Post Action method to add to controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(BettingViewModel viewModel)
{
return null;
}
BettingViewModel: I have added Selected property to BettingOffice class.
public class BettingViewModel
{
public string StartDate { get; set; }
public string EndDate { get; set; }
public List<BettingOffice> BettingOffices { get; set; }
}
public class BettingOffice
{
public bool Selected { get; set; }
public int BettingOfficeID { get; set; }
public string OfficeName { get; set; }
public string OfficeCode { get; set; }
public string IpAddress { get; set; }
public Nullable<bool> SupportOnly { get; set; }
public Nullable<int> SisSrNumer { get; set; }
public Nullable<bool> Local { get; set; }
public string Server { get; set; }
}
Hope this saves you some time.
View:
#using (Html.BeginForm("Createuser", "User", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<div class="form-group">
#Html.LabelFor(m => m.city, new { #class = "col-md-2 control-label" })
</div>
<div class="col-md-10">
<table>
<tr>
<td><input type="checkbox" name="city" value="Pune" id="1" />Pune</td>
<td><input type="checkbox" name="city" value="Banglore" id="2" />Banglore</td>
<td><input type="checkbox" name="city" value="Mumbai" id="3" />Mumbai</td>
</tr>
</table>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Create" />
</div>
</div>
}
[HttpPost]
public ActionResult Createuser(user user, string [] city)
{
var UserInfo = new user
{ Email =user.Email,Password=user.Password,Firstname=user.Firstname };
return View();
}
1. First of all, you are generating checkboxes with same name. So how you will be able to retrieve them on server end separately?
So declare some counter that gets incremented and name checkboxes uniquely.
#foreach (var item in Model.BettingOffices)
{
int counter=1;
var checkboxName = "selectedShops" + counter;
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="#checkboxName" value="#item.OfficeName">
counter++;
}
2. Now on submission of Form in your controller, get checkboxes as -
//Loop through the request.forms
for (var i = 0; i <= Request.Form.Count; i++)
{
var checkboxValue = Request.Form["selectedShops[" + i + "]"];
// Do whatever you want to with this checkbox value
}
For ticked values, you will probably get True value. Debug the retrieved value to write further code accordingly.
Try the following
your View is:
#foreach (var item in Model.BettingOffices)
{
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="selectedShops" value="#item.OfficeName">
}
Controller
[HttpPost]
public ActionResult Index(FormCollection collection)
{
if(!string.IsNullOrEmpty(collection["selectedShops"]))
{
string strSelectedShops = collection["selectedShops"];
}
}
Hi you can get the selected checkbox value using the bellow code it seem working fine fore me,
<script>
$(document).ready(function()
{
$("input[type=checkbox]").click(function()
{
var categoryVals = [];
categoryVals.push('');
$('#Category_category :checked').each(function() {
categoryVals.push($(this).val());
});
$.ajax({
type:"POST",
url:"<?php echo $this->createUrl('ads/searchresult'); ?>", //url of the action page
data:{'category': categoryVals},
success : function(response){
//code to do somethng if its success
}
});
}
}
</script>

Resources