So I have been making a simple contact form, and have written the code, and it sends the form, I receive it but it comes blank, no subject and no body.
Reviewing similar issues here on stackoverlow I found A LOT of php solutions but no asp.net that would come helpful in my scenario.
Here is the controller:
public ActionResult Send(Contact c)
{
if (ModelState.IsValid)
{
try
{
MailAddress sender = new MailAddress(c.Email, c.Name);
MailAddress recipient = new MailAddress("mymail#hotmail.com");
MailMessage Message = new MailMessage();
Message.From = sender;
Message.To.Add(recipient);
Message.Subject = c.Subject;
Message.Body = c.Msg;
Message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.Port = 587;
client.Credentials = new NetworkCredential("gmail#gmail.com", "password");
client.Send(Message);
return Redirect("/Success.html");
}
catch (Exception)
{
return Redirect("/Error.html");
}
}
else
{
return Redirect("www.google.com");
}
}
HTML:
<body>
<form action="/Mail/Send" method="post">
<div id="glavni">
<p>
<label for="TextName">Name:</label>
<input id="TextName" type="text" name="Name" required autofocus />
</p>
<p>
<label for="TextSubject">Subject:</label>
<input id="TextSubject" type="text" name="Subject" required />
</p>
<p>
<label for="TextMail">Email:</label>
<input id="TextMail" type="email" name="Email" required />
</p>
<p>
<label for="TextMsg">Unesite Poruku:</label>
<textarea id="TextMsg" type="text" name="Msg" rows="12" cols="20" ></textarea>
</p>
<p>
<button type="submit">Send</button>
</p>
</div>
</form>
MODEL:
public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
public string Subject { get; set; }
public string Msg {get; set;}
}
The Contact Models class props have the same names as html name attributes and for some reason sends empty emails.
Hope someone can shed some light!
Default all the actions in controllers are GET methods. So you have to specify the HTTP web method as POST
[HttpPost]
public ActionResult Send(Contact c)
Related
Error: NullReferenceException: Object reference not set to an instance of an object.
Web.Controllers.ManageController.ChangeUser(BaseViewModel model) in ManageController.cs
+
user.FirstName = model.ChangeUserViewModel.FirstName;
I cannot understand why I am getting this error, could you please help me find what I am doing wrong ?
What i am trying to achieve is updating the user information trough my viewmodel.
Can you please advise if the way i am trying to do it is correct?
BaseViewModel:
public class BaseViewModel
{
public IndexViewModel IndexViewModel { get; set; }
public ChangeUserViewModel ChangeUserViewModel { get; set; }
}
ChangeUserViewModel:
public class ChangeUserViewModel
{
[Required]
[StringLength(20, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 1)]
public string FirstName { get; set; }
[Required]
[StringLength(20, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 1)]
public string LastName { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Display(Name = "Profile Picture")]
[DataType(DataType.Upload)]
[MaxFileSize(5* 1024 * 1024)]
[AllowedExtensions(new string[] { ".jpg", ".png", ".jpeg", ".gif", ".tif" })]
public IFormFile ProfilePicture { get; set; }
}
Controller:
public async Task<IActionResult> Index()
{
var user = await GetCurrentUserAsync();
var model = new BaseViewModel
{
IndexViewModel = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user),
AuthenticatorKey = await _userManager.GetAuthenticatorKeyAsync(user),
},
ChangeUserViewModel = new ChangeUserViewModel
{
FirstName = user.FirstName,
LastName = user.LastName,
Email = user.Email
}
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangeUser(BaseViewModel model)
{
if (!ModelState.IsValid)
{
return RedirectToAction("Index", "Manage");
}
var user = await GetCurrentUserAsync();
if (user != null)
{
user.FirstName = model.ChangeUserViewModel.FirstName;
user.LastName = model.ChangeUserViewModel.LastName;
user.Email = model.ChangeUserViewModel.Email;
await _userManager.UpdateAsync(user);
}
return View("Index", model);
}
View:
#model BaseViewModel
#inject UserManager<ApplicationUser> UserManager
#{
ViewData["Title"] = "Manage your account";
}
<h2 class="content-heading pt-0">
<i class="fa fa-fw fa-user-circle text-muted mr-1"></i> User Profile
</h2>
<form asp-controller="Manage" asp-action="ChangeUser" method="post" class="form-horizontal" role="form" enctype="multipart/form-data">
<div class="row push">
<div class="col-lg-4">
<p class="text-muted">
Your account’s vital info.
</p>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
<div class="col-lg-8 col-xl-5">
<div class="form-group">
<label for="dm-profile-edit-firstname">Firstname</label>
<input asp-for="ChangeViewModel.FirstName" type="text" class="form-control" id="dm-profile-edit-firstname" name="dm-profile-edit-firstname" >
</div>
<div class="form-group">
<label for="dm-profile-edit-lastname">Lastname</label>
<input asp-for="ChangeViewModel.LastName" type="text" class="form-control" id="dm-profile-edit-lastname" name="dm-profile-edit-lastname">
</div>
<div class="form-group">
<label for="dm-profile-edit-email">Email Address</label>
<input asp-for="ChangeViewModel.Email" type="email" class="form-control" id="dm-profile-edit-email" name="dm-profile-edit-email">
</div>
<div class="form-group">
<label>Your Avatar</label>
<div class="push">
<img class="img-avatar" src="#Url.Action("ProfilePicture", "Account" )" alt="">
</div>
<div class="custom-file">
<input asp-for="ChangeViewModel.ProfilePicture" type="file" class="custom-file-input js-custom-file-input-enabled" data-toggle="custom-file-input" id="ProfilePicture" name="ProfilePicture">
<label class="custom-file-label" for="ProfilePicture">Choose a new avatar</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-alt-primary">
<i class="fa fa-check-circle mr-1"></i> Update Profile
</button>
</div>
</div>
</div>
</form>
It seems the controller didn't recieve the BaseViewModel when do post request from view. I suggest you could use Newtonsoft’s Json.NET instead of System.Text.Json.
Step1. Install the following Nuget package
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Step2.
If you are migrating from an existing project you’ll have a call to “AddMvc()” which you can then tack onto it like so :
services.AddMvc().AddNewtonsoftJson();
However in new .NET Core 3+ projects, you have a different set of calls replace MVC. So you’ll probably have one of the following :
services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddNewtonsoftJson();
Then, place your breakpoint in your controller code to check the value of BaseViewModel model.
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);
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.
I have a simple model and view. THough, the modelbinder seems to fail when trying to bind my model because I always receive NULL into my controller action. What am I doing wrong?
Razor code:
#model BikeSharing.Views.Shared.Widgets.Popups.LoginInputModel
#using (Ajax.BeginForm("Login",null, new AjaxOptions
{
UpdateTargetId = "login-partial-update",
HttpMethod = "POST"
}, new { id = "js-form-login" }))
{
#Html.TextBoxFor(x => x.Email, new {placeholder = "Email address"})
<div class="errormessage">
#Html.ValidationMessageFor(x=>x.Email)
</div>
#Html.PasswordFor(x => x.Password, new {placeholder = "Password"})
<div class="errormessage">
#Html.ValidationMessageFor(x => x.Password)
</div>
}
Controller Action:
[HttpPost]
public ActionResult Login(LoginInputModel lmod)
{
if (ModelState.IsValid)
{
// this code is never reached because lmod is always NULL
}
return PartialView("Widgets/Popups/_LoginInput", lmod);
}
Model code:
public class LoginInputModel
{
[Required(ErrorMessage = "Your email address is required.")]
[EmailAddress]
public string Email { get; private set; }
[Required(ErrorMessage = "Please provide your password.")]
[MinLength(6,ErrorMessage = "Your password is too short.")]
[MaxLength(50, ErrorMessage = "Your password is too long.")]
public string Password { get; private set; }
public LoginInputModel()
{
}
public LoginInputModel(string email, string password)
{
Email = email;
Password = password;
}
}
The form submit is done via jquery-unobtrusive-ajax and Ajax.BeginForm()
I am only firing it via $('#js-form-login').submit();
Rendered HTML in browser:
<form action="/Home/Login" data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#login-partial-update" id="js-form-login" method="post" novalidate="novalidate">
<input data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="Your email address is required." id="Email" name="Email" placeholder="Email address" type="text" value="">
<div class="errormessage">
<span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>
</div>
<input data-val="true" data-val-maxlength="Your password is too long." data-val-maxlength-max="50" data-val-minlength="Your password is too short." data-val-minlength-min="6" data-val-required="Please provide your password." id="Password" name="Password" placeholder="Password" type="password">
<div class="errormessage">
<span class="field-validation-valid" data-valmsg-for="Password" data-valmsg-replace="true"></span>
</div>
</form>
Try adding the FormBody prefix to hint to the ModelBinder to look in the POST body.
[HttpPost]
public ActionResult Login([FromBody]LoginInputModel lmod)
{
if (ModelState.IsValid)
{
// this code is never reached because lmod is always NULL
}
return PartialView("Widgets/Popups/_LoginInput", lmod);
}
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>