Passing null values to the parameter in controller after submit? - asp.net-mvc-3

The below code is sample I typed
After I submit passing null values to controller, In Controller I have used the Class name then value passing correctly but when i used the parameter it passing NULL values to the controller. Please give me a solution..
Controller:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string firstname)
{
LogonViewModel lv = new LogonViewModel();
var ob = s.Newcustomer(firstname)
return View(ob );
}
View:
#model IList<clientval.Models.LogonViewModel>
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
for (int i = 0; i < 1; i++)
{
#Html.LabelFor(m => m[i].UserName)
#Html.TextBoxFor(m => m[i].UserName)
#Html.ValidationMessageFor(per => per[i].UserName)
<input type="submit" value="submit" />
}
}
Model:
public class LogonViewModel
{
[Required(ErrorMessage = "User Name is Required")]
public string UserName { get; set; }
}
public List<ShoppingClass> Newcustomer(string firstname1)
{
List<ShoppingClass> list = new List<ShoppingClass>();
..
}

This:
[HttpGet]
public ActionResult Index() {
return View();
}
Does not give you this in your view:
#model IList<clientval.Models.LogonViewModel>
And this:
for (int i = 0; i < 1; i++) {
#Html.LabelFor(m => m[i].UserName)
#Html.TextBoxFor(m => m[i].UserName)
#Html.ValidationMessageFor(per => per[i].UserName)
<input type="submit" value="submit" />
}
Will not work with this:
[HttpPost]
public ActionResult Index(string firstname) {
LogonViewModel lv = new LogonViewModel();
var ob = s.Newcustomer(firstname)
return View(ob );
}
You're not sending a model to your view, and you're using a list in your view, but expecting a single string value in you controller. Something is very strange/wrong with your example, or your code.
Why do you have a IList as your model? If all you need is to render a form with a single input field. You should have code like this:
[HttpGet]
public ActionResult Index() {
return View(new LogonViewModel());
}
And the view:
#model clientval.Models.LogonViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
<input type="submit" value="submit" />
}
And the second action on the controller:
[HttpPost]
public ActionResult Index(LogonViewModel model) {
if (ModelState.IsValid) {
// TODO: Whatever logic is needed here!
}
return View(model);
}

Its working.. I have changed my controller as written below
Controller:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IList<LogonViewModel> obj)
{
LogonViewModel lv = new LogonViewModel();
var ob = lv.Newcustomer(obj[0].FirstName)
return View(ob );
}

Related

how can i get dropdownlist id in controller when we select an item using mvc4

I have dropdownlst which i have filled from database. Now i need to get the selected value in Controller do some manipulation. But null data will get. Code which i have tried.
##View##
#using (Html.BeginForm()) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
}
## Controller ##
public ActionResult ItemPurchased()
{
POS_DBEntities2 db = new POS_DBEntities2();
var query = from i in db.TBL_Account
where i.Type == "supplier"
select i;
ViewBag.PurSupName = new SelectList(query, "AccountId", "AccountName");
return PartialView("ItemPurchased", new List<PurchasedItem>());
}
##Controller##
public ActionResult GetPurchasedItem()
{
var optionsValue = this.Request.Form.Get("SupplierId");
return View();
}
You can try with below changes.
#using (Html.BeginForm("GetPurchasedItem","YourController")) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
<input type="submit" value="OK" />
}
Controller will be
[HttpPost]
public ActionResult GetPurchasedItem(string SupplierId)
{
var optionsValue = SupplierId;
//..............
return View();
}
It should work normally..

Required message for Unmapped field?

I have an unmapped field in asp.net MVC3. I want to display required message for this field but i can't. How can i display required messsage for unmapped fields? Is it possible ?
[Required(ErrorMessage = "Email alanı girilmelidir.")]
public string FirstEMail
{
get
{
return first_email;
}
set
{
first_email = value;
}
}
DAL:
modelBuilder.Entity<AbsKontak>().Ignore(p => p.FirstEMail);
View:
Html.LabelFor(p => p.FirstEMail)
Html.TextBoxFor(p => p.FirstEMail, new { class = "medium", disabled = "disabled", id = "txtFirstTel" })
Html.ValidationMessageFor(p => p.FirstEMail)
Is this your requirement, Please let me know if Iam wrong
Model:
[Required(ErrorMessage="FirstEMail is required")]
public string FirstEMail{get;set;}
Controller:
public ActionResult ValidatingFormMessages()
{
UserEmail objModel = new UserEmail();
objModel.FirstEMail = "xxx#yy.com";
return View(objModel);
}
[HttpPost]
public ActionResult Index(UserEmail coll)
{
if (ModelState.IsValid)
{
return RedirectToAction("yourActionName", "YourControllerName");
}
return View();
}
View:
#{Html.BeginForm();}
#Html.TextBoxFor(x => x.FirstEMail)
#Html.ValidationMessageFor(x => x.FirstEMail)
<input type="submit" id="btnSubmit" value="Submit" />
#{Html.EndForm();}

MVC3 passing incorrectly formatted datetime to Controller but correcting it in the Controller action gives ModelState error

Am I the only one having this problem or I am doing it in totally wrong direction.
I have a View passing DateTime value:
<div class="control-group">
#Html.Label("Appointment date", null, new { #class = "control-label" })
<div class="controls">
<div class="input-append">
#Html.TextBoxFor(model => model.Appointment.Client_PreferredDate, new { #readonly = "readonly" })
<span class="add-on margin-fix"><i class="icon-th"></i></span>
</div>
<p class="help-block">
#Html.ValidationMessageFor(model => model.Appointment.Client_PreferredDate)
</p>
</div>
The values are passed into the Controller action ( I can see the value, and I know it is giving the format that is not DateTime, i.e. it is going to be in dd-MM-yyyy). Then in the Controller I will reformat it.
[HttpPost]
public ActionResult RequestAppointment(General_Enquiry model, FormCollection fc)
{
model.Appointment.Client_PreferredDate = Utilities.formatDate(fc["Appointment.Client_PreferredDate"]);
ModelState.Remove("Appointment.Client_PreferredDate");
try
{
if (ModelState.IsValid)
{
model.Branch_Id = Convert.ToInt32(fc["selectedBranch"]);
model.Appointment.Branch_Id = Convert.ToInt32(fc["selectedBranch"]);
db.General_Enquiry.AddObject(model);
db.SaveChanges();
return RedirectToAction("AppointmentSuccess", "Client");
}
}
catch (Exception e)
{
Debug.WriteLine("{0} First exception caught.", e);
Debug.WriteLine(e.InnerException);
ModelState.AddModelError("", e);
}
return View(model);
}
The best I can do is to use ModelState.Remove(), which I feel really uncomfortable with. I suspect that when my Model is passed from the View to Controller, the ModelState is already set to Invalid before I can do anything in the Controller. Any ideas?
If I call the ModelState.Remove() everything went smoothly, the DateTime is accepted by SQL server database.
If at least I can update or 'refresh' ModelState at any point it'll fix my problem.
Cheers.
I'd recommend you using a view model and a custom model binder for the DateTime formats.
We start by defining this view model:
public class MyViewModel
{
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime PreferredDate { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
PreferredDate = DateTime.Now.AddDays(2)
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// model.PreferredDate will be correctly bound here so
// that you don't need to twiddle with any FormCollection and
// removing stuff from ModelState, etc...
return View(model);
}
}
a View:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.PreferredDate)
#Html.EditorFor(x => x.PreferredDate)
#Html.ValidationMessageFor(x => x.PreferredDate)
<button type="submit">OK</button>
}
and finally a custom model binder to use the specified format:
public class MyDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
that will be registered in Application_Start:
ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());

View "ChangePassword" in MVC 3

Can you help me to build my "ChangePassword" View in MVC3 ?
Here what I have tried to do:
ProfileTeacherController.cs
public ViewResult ChangePassword(int id)
{
var user = User.Identity.Name;
int inter = int.Parse(user);
var teachers = from t in db.Teachers
where t.AffiliationNumber == inter
select t;
Teacher teacher = new Teacher();
foreach (var teach in teachers)
{
teacher = teach;
}
return View(teacher);
}
[HttpPost]
public ActionResult ChangePassword(Teacher teacher)
{
if (ModelState.IsValid)
{
// How can I compare the two fields password in my view ?
db.Entry(teacher).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Edit", "ProfileTeacher", new { id = teacher.TennisClubID });
}
return View(teacher);
}
Here the ChangePassword (View)
#model TennisOnline.Models.Teacher
#{
ViewBag.Title = "ChangePassword";
}
<h2>Changement du mot de passe</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend></legend>
<div class="editor-label">
#Html.Label("Enter the new password")
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.Pin, new { value = Model.Pin })
</div>
<div class="editor-label">
#Html.Label("Confirm your password")
</div>
<div class="editor-field">
#Html.Password("ConfirmPassword")
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
So, How can I verify in my controller if the two passwords are the same, please ? Thanks in advance
In addition you can add the message to be shouwn when the two password are not the same in the Compare attribute.
[Compare("NewPassword", ErrorMessage = "The new password and confirm password do not match.")]
I would recommend the usage of a view model:
public class TeacherViewModel
{
...
[Compare("ConfirmPassword")]
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
now have your view take the view model and also your Post action.
In addition to that in your GET action you seem to have written some foreach loop which I don't see its usage. You could simplify:
[Authorize]
public ViewResult ChangePassword(int id)
{
var user = User.Identity.Name;
int inter = int.Parse(user);
var teacher = db.Teachers.SingleOrDefault(t => t.AffiliationNumber == inter);
return View(teacher);
}

MVC3 Can't get model back to the controller

I have the following ViewModel
public class RecommendationModel
{
public List<CheckBoxItem> CheckBoxList { get; set; }
}
public class CheckBoxItem
{
public string Text { get; set; }
public bool Checked { get; set; }
public string Link { get; set; }
}
With the following View
model Sem_App.Models.RecommendationModel
#using (Html.BeginForm())
{
for (int i = 0; i < Model.CheckBoxList.Count(); i++) {
#Html.CheckBoxFor(m => m.CheckBoxList[i].Checked)
#Html.DisplayFor(m => m.CheckBoxList[i].Text)
}
<input type="submit" value="Add To Playlist" />
}
With the following controller actions
//get
public ActionResult Recommendation()
{
RecommendationModel model = new RecommendationModel();
model.CheckBoxList = new List<CheckBoxItem>();
return PartialView(model);
}
//post
[HttpPost]
public ActionResult Recommendation(RecommendationModel model)
{
foreach (var item in model.CheckBoxList)
{
if (item.Checked)
{
// do something with item.Text
}
}
}
Problem is whenever I select some items and press the submit button the model returned has CheckBoxList as empty. How can I change my view to return the list of CheckBoxList? Trying
#Html.HiddenFor(m => m.checkBoxList) did not work for me
I think you nee something like this
#using (Html.BeginForm())
{
for (int i = 0; i < Model.CheckBoxList.Count(); i++) {
#Html.CheckBoxFor("Model.CheckBoxItem[" + i + "].Checked" , m => m.CheckBoxList[i].Checked)
#Html.DisplayFor("Model.CheckBoxItem[" + i + "].Text",m => m.CheckBoxList[i].Text)
}
Try adding the link as a hidden field: #Html.HiddenFor(m => m.CheckBoxList[i].Link )
Check how the checkbox input name is in the rendered html and also check the form action is sending to the corrent controller/action and the method is post
it should be something very simple.. create the action param as array with the same name of the "name" attribute form check box input
something like this
[HttpPost]
public ActionResult Delete(int[] checkName)
{
}

Resources