Getting model name attribute wrongly in forms c# - c#

I get my model name wrongly
instead of getting this way
<input class="text-box single-line" data-val="true" data-val-required="آدرس دریافت محصول اجباری میباشد." id="Address" name="Address" type="text" value="">
it renders it this way
<input class="text-box single-line" data-val="true" data-val-required="آدرس دریافت محصول اجباری میباشد." id="mod_Address" name="mod.Address" type="text" value="">
and my model defined this way:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using identity2.Models;
namespace identity2.ViewModels
{
public class OrderIndexViewModel
{
public products Product { get; set; }
public int Count_order { get; set; }
[Required(ErrorMessage = "آدرس دریافت محصول اجباری میباشد.")]
[Display(Name = "آدرس دریافت محصول")]
public string Address { get; set; }
[Display(Name = "سفارش به صورت آفلاین")]
public bool OfflineOrder { get; set; }
[Required(ErrorMessage = "تاریخ دریافت محخول را انتخاب کنید")]
[Display(Name = "تاریخ دریافت محصول")]
[RegularExpression(#"^([1][34]\d{2}\/((1[0-2]|[1-9]))\/(3[01]|[12][0-9]|[1-9]))$", ErrorMessage = "تاریخ معتبر نمیباشد")]
public string recive_date { get; set; }
}
}
and my view:
#model IList<identity2.ViewModels.OrderIndexViewModel>
#using System.Globalization;
#using identity2.Models;
#{
var mod = Model[0];
var dt = DateTime.Now;
PersianCalendar pc = new PersianCalendar();
var timenow = #pc.PearsianDate(dt);
}
<h4>سبد خرید</h4>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>توجه!</strong> <p>کلیه محصولات در روز پنج شنبه از ساعت 13 الی 19 به صورت رایگان ارسال میگردد در غیر این صورت هزینه پیک بر عهده مشتری می باشد.</p>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<table class="table table-responsive">
<tr>
<th>نام محصول</th>
<th>تعداد سفارش </th>
<th>قیمت کل</th>
<th>عملیات</th>
</tr>
#if (Model != null)
{
foreach (var protoype in Model)
{
var totalprice = #protoype.Product.price * #protoype.Count_order;
<tr>
<td>
#protoype.Product.title
</td>
<td>
#protoype.Count_order
</td>
<td>
#totalprice تومان
</td>
<td>
</i>
</td>
</tr>
}//end foreach
}
</table>
<div class="row">
<div class="col">
<h3>سفارش آنلاین</h3>
#using (Html.BeginForm("CartPaymentPost", "Order", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6">
#if (!ViewData.ModelState.IsValid)
{
#Html.ValidationSummary("", new { #class = "alert alert-warning alert-dismissible fade show" })
}
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => mod.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => mod.Address, new { #class = "form-control ", #rows = 5, #cols = 20, #id = "editor1" })
#Html.ValidationMessageFor(model => mod.Address, "آدرس الزامی میباشد", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => mod.recive_date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => mod.recive_date, null, "recive_date", new { htmlAttributes = new { #class = "form-control", #id = "PersianDate" } })
#Html.ValidationMessageFor(model => mod.recive_date, "تاریخ معتبر نمیباشد!", new { #class = "field-validation-error " })
</div>
</div>
<div class="form-check">
#Html.LabelFor(model => mod.OfflineOrder, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => mod.OfflineOrder, null, "OfflineOrder", new { htmlAttributes = new { #class = "form-check-input" } })
#Html.ValidationMessageFor(model => mod.OfflineOrder, "", new { #class = "field-validation-error " })
</div>
<div class="form-row">
<div class="col col-md-offset-2">
<input type="submit" value="پرداخت" class="btn btn-success" />
#*<a class="btn btn-default" href="/Order/BookPayment/"> <i class="fas fa-shopping-cart"></i> سفارش آفلاین </a>*#
</div>
</div>
}
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
And it cause a problem that cant bind my fields name to model when I use forms and what I cant figure out is why it just not recognizes address field but there no problem with other fields.

You need to use Html.TextArea (or write out the <input ...> by hand) instead of the Html.TextAreaFor.
You need to check the difference between control and controlFor (see below)
"Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.
Generally two things:
The typed TextBoxFor will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'
Using the typed TextBoxFor version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views."
Please refer the :
Html.Textbox VS Html.TextboxFor
difference between Html.TextBox and Html.TextBoxFor
ASP.NET MVC 4 override emitted html name and id

You try with this, It will work
#Html.TextArea("Address",mod.Address, new { #class = "form-control ", #rows = 5, #cols = 20, #id = "editor1" })

Related

ViewModel returning null into form, how do I fix this

I can't seem to get the values I entered from the form into my action createEmployee method in the controller I think the issue is the ViewModel I may be wrong but how do I fix this. The only thing I able to recieve back when I run the project the random number I generated, and null variables, also how do I add the inputted Employee back to list side note my Employee list is hard coded
View.cs
#using (Html.BeginForm("CreateEmployee", "/Employee", FormMethod.Post))
{
<div class="row">
<div class="col-lg-2">First Name</div>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Employee.Name, new { #class = "form-control" })
</div>
</div>
<br />
<div class="row">
<div class="col-lg-2">Last Name</div>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Employee.Surname, new { #class = "form-control" })
</div>
</div>
<br />
<div class="row">
<div class="col-lg-2">Date of Birth</div>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Employee.DateOfBirth, new { #class = "form-control" })
</div>
</div>
<br />
<div class="row">
<div class="col-lg-2">Department</div>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Employee.Department, new { #class = "form-control" })
</div>
</div>
<br />
<div class="modal-footer">
<button type="submit" class="btn btn-primary center-block">Complete</button>
</div>
}
EmployeeViewModel
public List<Fundi.HR.Web.Models.Employee> Employees { get; set; }
public Employee Employee { get; set; }
public EmployeeViewModel(List<Employee> found)
{
this.Employees = found;
}
Action EmployeeController
public ActionResult CreateEmployee(Employee emp)
{
if (ModelState.IsValid)
{
Random random = new Random();
int num = random.Next();
Employee empObj = new Employee();
List<Employee> employees = new List<Employee>();
empObj.EmployeeId = num;
empObj.Name = emp.Name;
empObj.Surname = emp.Surname;
empObj.DateOfBirth = emp.DateOfBirth;
empObj.Department = emp.Department;
employees.Add(empObj);
EmployeeViewModel em = new EmployeeViewModel(employees);
return View("Index", em);
}
else
{
return RedirectToAction("Index");
}
For a simple test, I used part of your code so that the value can be accepted, you can refer to the following:
View:
#model WebApplication38.Models.Employee
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("CreateEmployee", "Test", FormMethod.Post))
{
<div class="row">
<div class="col-lg-2">First Name</div>
<div class="col-lg-10">
#Html.TextBoxFor(m=>m.name, new { #class = "form-control" })
</div>
</div>
<br />
<div class="row">
<div class="col-lg-2">Last Name</div>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Surname, new { #class = "form-control" })
</div>
</div>
<br />
<div class="row">
<div class="col-lg-2">Date of Birth</div>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.DateOfBirth, new { #class = "form-control" })
</div>
</div>
<br />
<div class="row">
<div class="col-lg-2">Department</div>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Department, new { #class = "form-control" })
</div>
</div>
<br />
<div class="modal-footer">
<button type="submit" class="btn btn-primary center-block">Complete</button>
</div>
}
Controller and result:

Bootstrap Modal showing with blank edit data

I am using a modal bootstrap but my data is not loading into the bootstrap even though I am passing it trough from the controller.
My Grid pulls in data from a list for Notes Object
#foreach (var notes in Model) {
<tr>
<td>#notes.LastModifedDate</td>
<td>#notes.LastModifiedBy</td>
<td>#notes.Notes </td>
<td>
<p>#notes.Id</p> <i class="glyphicon glyphicon-pencil"></i>Edit
|<p>#notes.Id</p> <i class="glyphicon glyphicon-trash"></i>Delete
</td>
</tr>
}
I am using the following to Return the data to the popup.
public ActionResult NotesEditPopupPartial(int id ) {
var record = _context.MISNotes.Where(w => w.Id == id).FirstOrDefault();
return PartialView("NotesEditPopupPartial", record);
}
And using the following call to load the data but the data is not in the model for me to edit the text fields are still blank.
<script>
var AddOrEditNotes = function (id) {
var url = "/MISOjbects/NotesEditPopupPartial?id=" + id;
$("#myModalBodyDiv1").load(url, function () {
$("#MyEditUpateModal").modal("show");
})
}
</script>
<script>
function EditModal(id) {
$("#editMode").val(id);
}
</script>
My Modal
<div class="modal fade" id="NotesEditPopupPartial">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">Notes Entry</h3>
</div>
<div class="modal-body" id="myModalBodyDiv1">
<div>
<input type="text" name="linkId" id="linkId" />
#using (Html.BeginForm("SaveCaseNotes", "MISObjects", FormMethod.Post, new { #id = "myNotesEditForm", #name = "myNotesEditForm", enctype = "multipart/form-data" })) {
<form id="myForm" asp-action="">
<div asp-validation-summary="All" class="text-danger"></div>
#Html.LabelFor(model => model.Title)
#Html.TextBoxFor(model => model.Title, new { #class = "form-control", #placeholder = "Title" })
#Html.ValidationMessageFor(model => model.Title, string.Empty, new { #style = "color:red;" })
<div class="form-group">
#Html.LabelFor(model => model.Notes, new { #class = "col-lg-2 control-label" })
<div class="col-lg-9">
#Html.TextAreaFor(model => model.Notes, new { #class = "form-control", #row = 5 })
</div>
</div>
#Html.LabelFor(model => model.DateActioned)
#Html.EditorFor(model => model.DateActioned, new { htmlAttributes = new { #class = "form-control datetimepicker" } })
#Html.ValidationMessageFor(model => model.DateActioned)
#Html.DisplayNameFor(model => model.LastModifiedBy)
#Html.LabelFor(model => model.LastModifiedBy)
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<div class="modal-footer">
<button type="submit" id="btnEditSave" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
}
</div>
<div style="text-align:center;display:none" id="loaderDiv">
<img src="~/Content/InternetSlowdown_Day.gif" width="150" />
</div>
</div>
</div>
Wrap your modal with div:
<div id="modalWrapper">
<div class="modal fade" id="NotesEditPopupPartial">
...
</div>
</div>
and then load and show the modal:
$("#modalWrapper").load(url, function () {
$("#NotesEditPopupPartial").modal("show");
})
<script>
var AddOrEditNotes = function (id) {
var url = "/MISOjbects/NotesEditPopupPartial?id=" + id;
$("#myModalBodyDiv1").load(url, function () {
$("#MyEditUpateModal").modal("show");
})
}
</script>
<script>
function EditModal(id) {
$("#editMode").val(id);
}
</script>
According to your code, I didn't find where you call the AddorEditNotes function to call the NotesEditPopupPartial action and display the partial, and in the EditModel method, you also didn't call the action method to show the partial, so, the popup modal is blank.
In my opinion, I suggest you put the bootstrap Modal on the main page (with note grid), because the trigger button (Edit hyperlink) is on this page. Then, in the hyperlink click event, you could use JQuery Ajax to call the action method and load the partial view and put it on the Bootstrap Modal.
Sample code as below:
Code in the Main page:
#model IEnumerable<NetMvcSample.Models.Note>
#{
ViewBag.Title = "ShowNotes";
}
<h2>ShowNotes</h2>
<script>
function EditModal(id) {
event.preventDefault(); // prevent the hyperlink default event.
$.ajax({
type: "POST",
url: "/Home/NotesEditPopupPartial", //change the url to your owns.
data: '{id: '+ id + "}",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data)
//put the partial view in the modal content.
$('#myModalBodyDiv1').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
}
</script>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.LastModifyDate)
</th>
<th>
#Html.DisplayNameFor(model => model.LastModifiedBy)
</th>
<th>
#Html.DisplayNameFor(model => model.Notes)
</th>
<th></th>
</tr>
#foreach (var notes in Model) {
<tr>
<td>
#notes.LastModifyDate
</td>
<td>
#notes.LastModifiedBy
</td>
<td>
#notes.Notes
</td>
<td>
<p>#notes.Id</p> <i class="glyphicon glyphicon-pencil"></i>Edit
|<p>#notes.Id</p> <i class="glyphicon glyphicon-trash"></i>Delete
</td>
</tr>
}
</table>
<div class="modal fade" id="NotesEditPopupPartial">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">Notes Entry</h3>
</div>
<div class="modal-body" id="myModalBodyDiv1">
</div>
</div>
</div>
</div>
Code in the controller method:
[HttpPost]
public ActionResult NotesEditPopupPartial(int id)
{
var record = GetNotes().Where(c => c.Id == id).FirstOrDefault();
return PartialView("NotesEditPopupPartial", record);
}
public ActionResult SaveCaseNotes(Note note)
{
// do something
return View();
}
Code in the NotesEditPopupPartial view (NotesEditPopupPartial.cshtml):
#model NetMvcSample.Models.Note
#using (Html.BeginForm("SaveCaseNotes", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Note</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.LastModifyDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastModifyDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastModifyDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastModifiedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastModifiedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastModifiedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Notes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Notes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Notes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The output like this:

ActionLink controller is getting called twice

I have a table view with list of roles and an action link to create new roles. Below is my roles.cshtml page
#model List<ExpenCare.Models.CompanyRole>
<div class="row">
#Html.Partial("_RightSidePane")
<div class="col-10 col-sm-8 col-xs-8 col-md-10">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade" id="list-Roles-Content" role="tabpanel" aria-labelledby="list-Roles"></div>
#using (#Html.BeginForm("UpdateRoles", "Admin", FormMethod.Post))
{
<table class="table">
<tr>
<th>
Name
</th>
<th>
Enable
</th>
</tr>
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#Html.HiddenFor(m => m[i].Id)
#Html.HiddenFor(m => m[i].Name)
#Html.DisplayFor(m => m[i].Name)
</td>
<td>
#Html.EditorFor(m => m[i].Enabled, new { #checked = "checked" })
</td>
</tr>
}
</table>
<p><input type="submit" value="Save Changes" /></p>
<p style="color:green; font-size:12px;">#ViewBag.Message</p>
<p>
#Html.ActionLink("Create new Roles", "ViewCreateRoles", "Admin", null, new { id = "CreateRoles", #class = "appao-btn" })
</p>
}
</div>
</div>
</div>
"Create new roles" button calls to ViewCreateRoles method in admin controller, which stated below.
public ActionResult ViewCreateRoles()
{
return View("Roles/CreateRoles");
}
In CreateRoles.cshtml page user can create a role and submit. when submitting it redirects to action CreateRoles in the same admin controller.
#model ExpenCare.Models.CompanyRole
#{
ViewBag.Title = "CreateRoles";
}
<div class="row">
#Html.Partial("_RightSidePane")
<div class="col-10 col-sm-8 col-xs-8 col-md-10">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="list-Profile-Content" role="tabpanel" aria-labelledby="list-Profile">
#using (Html.BeginForm("CreateRoles", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Enabled, "Enable", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Enabled)
#Html.ValidationMessageFor(model => model.Enabled, "", new { #class = "text-danger" })
</div>
</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>
</div>
</div>
</div>
Below is the CreateRoles methodin admin controller.
public ActionResult CreateRoles(CompanyRole role)
{
List<CompanyRole> roles;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:1888/api/");
var responseTask = client.PostAsJsonAsync("CompanyRoles", role);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<List<CompanyRole>>();
readTask.Wait();
roles = readTask.Result;
return View("Roles/Roles", model: roles);
}
else
{
ViewBag.Message = "not updated.";
return View("Roles/CreateRoles");
}
}
After creating a role on success user is redirecting to roles.cshtml mentioned above which shows all the roles. My problem is that my process of adding a role (go to roles page-> create new role-> redirect to roles page) is working fine. But just after redirecting to the roles page I get "An exception of type 'System.Web.Http.HttpResponseException' occurred in ExpenCare.dll but was not handled in user code" error in my web api which is getting called in CreateRoles. when I debug the process I see that after going to "Dispose" method of admin contoller "CreateRoles" method is getting called again and null "CompanyRole role" data is passed to the web API. I dunno how it is getting called again. I checked in google and tried removing all "#" from href and src of my view and layout pages, but it is still not working. I can't find why the same method is getting called twice without the button click.

How can i change my model value on button click in Razor?

Currently im working on a project where i have two buttons.
"Windows Login" and "Login". When i click on "Windows Login" i would like to submit the form and before submitting i would like to change my model choosenProvider string property value to "Windows".
Here is my model:
public class LogInUserViewModel
{
public LogInUserViewModel() { }
[Required]
[Display(Name = "Name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
public string ReturnUrl { get; set; }
public string ChoosenProvider { get; set; } = "idsrv";
}
And here is my Razor page:
<body>
<div class="background">
<div class="login-area">
<br />
<div class="login-title">Control Unit Registry</div>
<br />
#Html.ValidationSummary(true, "", new { #class = "text-warning-login" })
<div class="holder-form-login">
<div class="form-group">
<div class="text-login">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "input-name-login" } })
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-warning-login" })
</div>
</div>
</div>
<br />
<div class="form-group">
<div class="text-login">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "input-password-login" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-warning-login" })
</div>
</div>
</div>
</div>
#Html.HiddenFor(x => x.ChoosenProvider)
<div class="form-group">
<div class="holder-button-login">
<br />
<input type="submit" value="Login" class="button-login" />
</div>
</div>
<br />
<br />
<div class="form-group">
<div class="holder-button-login">
<br />
<input type="submit" value="Windows Login" class="button-login" onclick="chooseWindowsProvider()" />
</div>
</div>
<br />
<br />
<br />
<br />
<div class="link-register-login">
Register
</div>
</div>
</div>
</body>
This is the only page what i have in razor and it completely drives me mad.
You can see that i was experiencing with:
#Html.HiddenFor(x => x.ChoosenProvider)
And javascript onclick() but it did not change the value.
So to SUM UP:
I dunno how to change choosenProvider property value to "Windows", and then submit the form, on button click.
Any help is appreciated.
Okey i finally found it out, i hope it will help someone in the future, also please not that intelisense will might tell you that x or y function on field dont even exists but they do.
So the solution was that js was executed later then the submit, so the thing you need to do is:
Change the button type to <input type="button" from type="submit"
Then insert the following script at the end of your file
<script>
function chooseWindowsProvider() {
document.getElementById('ChoosenProvider').value = 'Windows';
document.getElementById('loginForm').submit();
}
</script>
So we are basically submitting the form from js rather then from the button so this way we can assign the string value before the submitting.
Some additional info:
#Html.HiddenFor(x => x.ChoosenProvider)
Already contains an id because its HTML result is:
<input id="ChoosenProvider" name="ChoosenProvider" type="hidden" value="idsrv" />
And finally how you can add an id to your form:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "loginForm"}))

How works #Html.ListBoxFor with a list of object?

I'm pretty new with asp.net and even if I see some similar question here, I couldn't solve my problem.
I have a list of an object Permission ( compose with an id, a name, a description etc.. ) and I want to use this list to create a multiple select with #Html.ListBoxFor to obtain a select containing option like that:
<option value="Id of the permission">Name of the permission</option>
Here is my controller:
[ChildActionOnly]
public PartialViewResult _GroupAdd(ManagerGroupViewModel groupe)
{
if (groupe != null)
{
//Here isn't important
return PartialView(groupe);
}
else
{
ManagerGroupViewModel grp = new ManagerGroupViewModel();
List<PermissionDTO> list = FactoryBO.Users.PermissionBO.GetAll();
grp.permissionList = list;
return PartialView("_GroupAdd", grp);
}
}
here my partial view:
#using (Ajax.BeginForm("_GroupAdd", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
{
<form class="col s12">
<div class="row">
<div class="input-field col s12">
#Html.LabelFor(model => Model.groupe.Name, "Group name")
#Html.EditorFor(model => Model.groupe.Name, new { htmlAttributes = new { #class = "validate" } })
#Html.ValidationMessageFor(model => Model.groupe.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="input-field col s12">
</div>
#Html.ListBoxFor(model => model.groupe.Permissions, new SelectList(Model.permissionList) )
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
</form>
}
For the moment, I just obtain this :
<li class="">
<span><input type="checkbox"><label></label>{"Id":FHdqsbg,"Description":"Menu Principal. NOTA: Par defaut ","Name":"AccessMainMenu"}</span>
</li>
if someone can help me :)
Add a DropDownListFor in you Partial, like that:
<div class="input-field col s12">
#Html.LabelFor(model => Model.groupe.Name, "Group name")
#Html.EditorFor(model => Model.groupe.Name, new { htmlAttributes = new { #class = "validate" } })
#Html.ValidationMessageFor(model => Model.groupe.Name, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.permissionList.UserRoleId)
#Html.DropDownListFor(m => m.UserRoleId, new SelectList(model.permissionList, "RoleId", "RoleName"))
</div>
Change UserRoleId andRoleName to the actual names of your fields in the list.
References:
DropDownListFor
SO Example

Categories