Updating multiple list items within same view - asp.net-mvc-4

I am trying to make a default value take application, My view loads all my value with one editor. My controller is not getting any of the data from the view?
I want to be able to edit all my value at the same time? How can I do this
Model Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Demo.Models.Admin
{
public class MerchantPackageTransactionModel
{
public MerchantPackageTransactionModel()
{
FeatureList = new List<PackageFeatureModel>();
}
public int PackageId { get; set; }
public string PackageName { get; set; }
public string Image { get; set; }
public List<PackageFeatureModel> FeatureList { get; set; }
}
public class PackageFeatureModel
{
public int FeatureId { get; set; }
public string FeatureName { get; set; }
public string Type { get; set; }
public string DefaultValue { get; set; }
public string Value { get; set; }
}
}
View Code
#model Demo.Models.Admin.MerchantPackageTransactionModel
#{
ViewBag.Title = "CreatePackageTransaction";
Layout = "~/Themes/green/Views/Shared/_AdminDashboard.cshtml";
}
#using (Html.BeginForm())
{
<fieldset>
<legend>MerchantPackageTransactionModel</legend>
#Html.HiddenFor(model => model.PackageId)
<div class="editor-label">
#Html.LabelFor(model => model.PackageName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PackageName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Image)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Image)
</div>
#foreach (var item in Model.FeatureList)
{
#Html.HiddenFor(model => item.FeatureId)
<div class="editor-label">
#Html.Label("Feature Name")
</div>
<div class="editor-field">
#Html.DisplayFor(model => item.FeatureName)
</div>
<div class="editor-label">
#Html.Label("Type")
</div>
<div class="editor-field">
#Html.DisplayFor(model => item.Type)
</div>
<div class="editor-label">
#Html.Label("Default Value")
</div>
<div class="editor-field">
#Html.DisplayFor(model => item.DefaultValue)
</div>
<div class="editor-label">
#Html.Label("Value")
</div>
<div class="editor-field">
#Html.EditorFor(model => item.Value)
</div>
}
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Controller code
public ActionResult CreatePackageTransaction(MerchantPackageTransactionModel objMerchantPackageTransactionModel)
{
foreach (var item in objMerchantPackageTransactionModel.FeatureList)
{
if (ModelState.IsValid)
{
GR.InsertOrUpdate(item);
}
}
GR.Save();
return View(objMerchantPackageTransactionModel);
}

What is happening is, because you are using
#Html.EditorFor(model => item.Value)
that is a command directly associated with the model and it is being used to render an input not accessed from the model (item), it is rendering an input html with the "wrong" name:
<input class="text-box single-line" id="item_Value" name="item.Value" type="text" value="">
when it should be
<input class="text-box single-line" id="FeatureList_0__Value" name="FeatureList[0].Value" type="text" value="">
And, as name does not match with the one from the model (FeatureList), the framework cannot do the automatic bind when the request hits the server.
You have a two options to fix it:
Create the html by hand, setting the correct (expected) name; or:
In the iteration use an index so that the EditorFor generates the input with the expected name:
#{
var index = 0;
}
#foreach (var item in Model.FeatureList)
{
#Html.HiddenFor(model => model.FeatureList[index].FeatureId)
<div class="editor-label">
#Html.Label("Feature Name")
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.FeatureList[index].FeatureName)
</div>
<div class="editor-label">
#Html.Label("Type")
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.FeatureList[index].Type)
</div>
<div class="editor-label">
#Html.Label("Default Value")
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.FeatureList[index].DefaultValue)
</div>
<div class="editor-label">
#Html.Label("Value")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FeatureList[index].Value)
</div>
index++;
}
I have tested and it just work worked fine. Have a nice weekend! Regards.

Related

HiddenFor value is empty

I have a view
#using (#Html.BeginForm())
{
<div class="form-horizontal">
<h4>Person</h4>
<hr/>
#Html.ValidationSummary(true)
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
#Html.HiddenFor(x => x.PersonId)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
#Html.ValidationMessageFor(m => m.Name)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Gender)
#Html.DropDownListFor(m => m.Gender, Html.GetEnumSelectList(typeof(Gender)))
#Html.ValidationMessageFor(m => m.Gender)
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"/>
</div>
</div>
</div>
}
And ViewModel
public class Person
{
[HiddenInput]
public int PersonId { get; set; }
[Required]
public string Name { get; set; }
public Gender Gender { get; set; }
}
public enum Gender
{
Male,
Female
}
The problem is validation complaints about PersonId being null.
It renders in browser as such (see, value is empty, but should be zero).
<div class="form-group">
<input data-val="true" data-val-required="The PersonId field is required." id="PersonId" name="PersonId" value="" type="hidden">
</div>
Could you please help? I'm using ASP.NET Core 1.8 RC2
Maybe you don't initialize object (Person) so the value is empty.
You could do as below then the value will not be empty.

ViewModel List object return Null on HTTPPost

I am posting a form back to the server, the values are always null.
Model:
public class RDetailsViewModel
{
public RDetailsMaster RDetailsMaster { get; set; }
public ETransaction ETransaction { get; set; }
}
public class RDetailsMaster
{
[Required]
public List<QE_DROPDOWN_MST> Master_EQ { get; set; }
[Required]
public List<QE_DROPDOWN_MST> Master_BASIS { get; set; }
[Required]
public List<QE_DROPDOWN_MST> Master_TE { get; set; }
[Required]
public List<QE_DROPDOWN_MST> Master_ALOP { get; set; }
[Required]
public List<QE_DROPDOWN_MST> Master_RISK { get; set; }
[Required]
public List<QE_DROPDOWN_MST> Master_EXCESS { get; set; }
[Required]
public List<QE_DROPDOWN_MST> Master_CType { get; set; }
}
Controller:
[HttpPost]
public ActionResult RDetails(RDetailsViewModel ObjR)
{
return view();
}
My View :
#model QMS_ERater.ViewModels.RDetailsViewModel
#{
ViewBag.Title = "RDetails";
}
<script src="~/Scripts/EAR/RDetails.js"></script>
#using (Html.BeginForm("RDetails", "RDetails", FormMethod.Post))
{
<h2>RDetails</h2>
<div class="well well-sm">
<div id="divDetail101" runat="server">
<div class="row">
<div class="col-sm-4">
<span style="vertical-align: top; color: Red">*</span> EQ :
</div>
<div class="col-sm-3">
#Html.DropDownListFor(m => m.ETransation.EQ, new SelectList(Model.RDetailsMaster.Master_EQ, "VALUE", "DESCRIPTION"), "--Select--", new { style = "width: 100%;" })
</div>
<div class="col-sm-2">
<span style="vertical-align: top; color: Red">*</span> On First Loss Basis :
</div>
<div class="col-sm-3">
#Html.DropDownListFor(m => m.ETransation.BASIS, new SelectList(Model.RDetailsMaster.Master_BASIS, "VALUE", "DESCRIPTION"), "--Select--", new { style = "width: 100%;" })
</div>
<div class="col-sm-4">
<span style="vertical-align: top; color: Red">*</span> Terrorism :
</div>
<div class="col-sm-3">
#Html.DropDownListFor(m => m.ETransation.IS_TE, new SelectList(Model.RDetailsMaster.Master_TE, "VALUE", "DESCRIPTION"), "--Select--", new { style = "width: 100%;" })
</div>
<div class="col-sm-2">
<span style="vertical-align: top; color: Red">*</span> ALOP :
</div>
<div class="col-sm-3">
#Html.DropDownListFor(m => m.ETransation.IS_ALOP, new SelectList(Model.RDetailsMaster.Master_ALOP, "VALUE", "DESCRIPTION"), "--Select--", new { style = "width: 100%;" })
</div>
<div class="col-sm-4">
<span style="vertical-align: top; color: Red">*</span> Wet Risk :
</div>
<div class="col-sm-3">
#Html.DropDownListFor(m => m.ETransation.IS_RISK, new SelectList(Model.RDetailsMaster.Master_RISK, "VALUE", "DESCRIPTION"), "--Select--", new { style = "width: 100%;" })
</div>
</div>
</div>
<input type="submit" value="Submit" />
</div>
}
When I am trying call post method objR return NULL value for only List objects.
Any help would be greatly appreciated.
Thanks in advance!

Captcha is not loading While adding Screen restriction

I am developing my project in MVC. In registration page i am using captcha control. It is working Fine. But my problem is i am adding screen restriction to some of my pages. While adding screen restriction captcha is not getting loaded.
can anyone please help me?
I have added the screen restriction code below
public class ScreenRestriction : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var routeData = filterContext.HttpContext.Request.RequestContext.RouteData;
string currentAction = routeData.GetRequiredString("action");
string currentController = routeData.GetRequiredString("controller");
string currentArea = routeData.Values["area"] as string;
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
var session = filterContext.HttpContext.Session;
if ((currentAction != "Login" && currentAction != "Create" && currentAction != "GetUser" && currentAction != "Index" ) == true)
{
if (session["UserID"] == null)
{
if (request.IsAjaxRequest())
{
response.StatusCode = 590;
}
else
{
var url = new UrlHelper(filterContext.HttpContext.Request.RequestContext);
response.Redirect(url.Action("Login", "CU"));
}
filterContext.Result = new EmptyResult();
}
else
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
}
}
}
base.OnActionExecuting(filterContext);
}
Screen restriction in Filters
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new ScreenRestriction());
}
}
I have added the registration page code below
View--
#model SYTMain.Models.tblUser
#using CaptchaMvc.HtmlHelpers
#using CaptchaMvc;
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout_for_registration.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>tblUser</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MiddleName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MiddleName)
#Html.ValidationMessageFor(model => model.MiddleName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EmailID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmailID)
#Html.ValidationMessageFor(model => model.EmailID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AddressId, "Address1")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.tblAddress.Address1)
#Html.ValidationMessageFor(model => model.tblAddress.Address1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AddressId, "Address2")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.tblAddress.Address2)
#Html.ValidationMessageFor(model => model.tblAddress.Address2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MobileNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MobileNumber)
#Html.ValidationMessageFor(model => model.MobileNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.WorkNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.WorkNumber)
#Html.ValidationMessageFor(model => model.WorkNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HomeNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HomeNumber)
#Html.ValidationMessageFor(model => model.HomeNumber)
</div>
#Html.Captcha(3)
<br />
<p class="Error"> #ViewBag.ErrMessage </p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(tblUser tbluser)
{
string val = System.Configuration.ConfigurationManager.AppSettings["CUTypeId"];
int code = Convert.ToInt32(val);
Session["Emailid"] = tbluser.EmailID.Trim();
if (ModelState.IsValid && this.IsCaptchaValid("Captcha Not Valid") )
{
EmailManager.SendConfirmationEmailName(tbluser.EmailID, tbluser.FirstName);
tbluser.UserTypeId = code;
db.tblUsers.Add(tbluser);
db.SaveChanges();
return RedirectToAction("Login", new { Email = tbluser.EmailID });
}
ViewBag.BusinessCategoryId = new SelectList(db.tblBusinessCategories, "BusinessID", "BusinessName", tbluser.BusinessCategoryId);
ViewBag.UserTypeId = new SelectList(db.tblUserTypes, "UserTypeID", "UserType", tbluser.UserTypeId);
ViewBag.AddressId = new SelectList(db.tblAddresses, "AddressID", "Address1", tbluser.AddressId);
ViewBag.ErrMessage = "Error: Captcha not valid";
return View(tbluser);
}

How to check compare Validation in View in MVC

In MVC 4 Need to check From And To Values in View like CompareValidator whether the To Value is greater than From Value?
Model:
[Required(ErrorMessage = "Please Enter From")]
public int FROM_RECORDVALUE { get; set; }
[Required(ErrorMessage = "Please Enter To")]
public int TO_RECORDVALUE { get; set; }
View :
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label class="defaultlable">
#Model.getPickListMaster().getPickListHeaderName("RECORDVALUE") From
</label>
#Html.TextBoxFor(model => model.FROM_RECORDVALUE, new { #class = "form-control", #maxlength = #Model.getPickListMaster().MAX_LENGTH })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="defaultlable">
#Model.getPickListMaster().getPickListHeaderName("RECORDVALUE") To
</label>
#Html.TextBoxFor(model => model.TO_RECORDVALUE,new { #class = "form-control", #maxlength = #Model.getPickListMaster().MAX_LENGTH})
</div>
</div>
</div>
How can i achieve this?. Please give me suggestions.

Details View is displaying “System.Data.Entity.DynamicProxies

I dont know how to solve the proble, something is wrong, please help!
the problem is:
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Student_0C394DD28745C7061A0EB9964A9FAD1A77E5EB1B24F61D61E2229472BCC850EE', but this dictionary requires a model item of type 'ContosoUniversity.ViewModels.DetailsViewModel'.
StudentController:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = _db.Students.Include(m => m.Comments).SingleOrDefault(x => x.ID == id);
if (student == null)
{
return HttpNotFound();
}
var model = new DetailsViewModel
{
Comment = new Comment(),
Student = student,
Comments = student.Comments.OrderBy(c => c.Id).ToList()
};
return View(student);
}
View:
#model ContosoUniversity.ViewModels.DetailsViewModel
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Student</h4>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.Student.LastName)
</dt>
<dd>
#Html.DisplayFor(model => model.Student.LastName)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Student.FirstMidName)
</dt>
<dd>
#Html.DisplayFor(model => model.Student.FirstMidName)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Student.EnrollmentDate)
</dt>
<dd>
#Html.DisplayFor(model => model.Student.EnrollmentDate)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Student.Enrollments)
</dt>
<dd>
<table class="table">
<tr>
<th>Course Title</th>
<th>Grade</th>
</tr>
#foreach (var item in Model.Enrollments)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Course.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Grade)
</td>
</tr>
}
</table>
</dd>
</dl>
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
#Html.ValidationSummary(true)
<input type="hidden" value="#Model.Comment.Id" name="commentId" />
<div class="form-group">
#Html.LabelFor(model => model.Comment.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment.Name)
#Html.ValidationMessageFor(model => model.Comment.Name)
</div>
</div>
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Comment.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment.Email)
#Html.ValidationMessageFor(model => model.Comment.Email)
</div>
</div>
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Comment.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment.Text)
#Html.ValidationMessageFor(model => model.Comment.Text)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div id="comments">
#foreach (var c in Model.Comments)
{
#Html.Partial("_Comment", c)
}
</div>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { id = Model.Student.ID }) |
#Html.ActionLink("Back to List", "Index")
</p>
DetailsViewModel:
public Student Student { get; set; }
public List<Comment> Comments { get; set; }
public Comment Comment { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
Comment model:
public int Id { get; set; }
public int CommentId { get; set; }
public Student Student { get; set; }
[Required]
public string Name { get; set; }
[EmailAddress]
public string Email { get; set; }
[Required]
public string Text { get; set; }
Student Model:
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public string FullName
{
get
{
return string.Join(" ", FirstMidName, LastName);
}
}
public virtual ICollection<Enrollment> Enrollments { get; set; }
public List<Comment> Comments { get; set; }
if somebody didnt understand Im trying add commentaries list at Details page with partial view.
You are trying to pass a Student Object to the View where you defined waht object it will handle Namely: #model ContosoUniversity.ViewModels.DetailsViewModel
You need to either in your controller pass the view a DetailsViewModel or you have to rethink what you are doing/ need to do, and make the view handle object Student.
i dont know where this model is but something like:
#model ContosoUniversity.Models.Student
Assuming you have a DisplayTemplates folder in your Shared Views folder named _Comment.cshtml (i.e. a path like /Views/Shared/DisplayTemplates/_Comment.cshtml) you should try the following:
Rename _Comment.cshtml to Comment.cshtml
Replace the following:
<div id="comments">
#foreach (var c in Model.Comments)
{
#Html.Partial("_Comment", c)
}
</div>
with the following:
#Html.DisplayFor(model => model.Comments)
I just fought with this myself and the underscore in the filename was what was breaking things.