MVC4 sending model propert id to controller class - asp.net-mvc-4

How to send id of a model property Name to Controller class in an MVC4 application
public class{
public Name{get;set;}
}
For Accesing name using id of that property
Update:
Here if change Name using jquery at runtime i want to send the changed name id to the controller class
UPDate:
This is my VIew
<script type="text/javascript">
$(function () {
$('.editor input').blur(function () {
$(this).hide();
$(this).closest('p').find('label').html($(this).val()).show();
});
$('.editor label').click(function () {
$(this).hide();
$(this).closest('p').find('input').show();
});
});
#using (Html.BeginForm("Homepage", "Home", FormMethod.Post))
{
<div class="editor">
<p>
#Html.LabelFor(x => x.Name, Model.Name)
#Html.EditorFor(x => x.Name)
<input type="submit" value="OK" />
</p>
<p>
#Html.LabelFor(x => x.Company, Model.Company)
#Html.EditorFor(x => x.Company)
<input type="submit" value="OK" />
</p>
<p>
#Html.LabelFor(x => x.City, Model.City)
#Html.EditorFor(x => x.City)
<input type="submit" value="OK" />
</p>
</div>
<input type="submit" value="OK" />
}
This is my model
public class Details
{
public string Name
{ get; set; }
public string Company
{ get; set; }
public string City
{ get; set; }
}
This is my COntroller methods
public ActionResult Homepage(Details d)
{
d.Name = "Rakesh";
d.Company = "TCS";
d.City = "DElhi";
return View(d);
}
[HttpPost, ActionName("Homepage")]
public ActionResult Indexof(Details d)
{
return View(d);
}
Here i am editing and sending data to the controller but my problem is when i click on Rakesh for example and change the name then i need to click button twice then only the changed data is sent to the controller class

Model:
public class SomeModel {
public string Name { get; set; }
}
Controller:
[HttpPost]
public ActionResult YourAction( SomeModel m )
{
if( ModelState.IsValid )
{
// use model
var name = m.Name;
return RedirectToAction( "Index", "Home" );
}
return View( m );
}
If this isn't what you need, please clarify what's this "id" you're talking about.

Related

How to solve empty model trouble using both Ajax.BeginForm and Html.BeginForm in MVC

I am new to MVC and stuck in passing modal to controller.
I have read many similar threads in SO, to no avail.
Here, I have a view for entering order details.
User will enter order item details (using ajax.BeginForm) and when he clicks save, whole order will be saved in backend (using Html.BeginForm). Ajax.BeginForm is working properly and passing + displaying records properly. But Html.BeginForm is passing model as nothing.
Here is my code ...
My Models
public class OrderItemsModel
{
public string SrNo { get; set; }
public int? ItemCode { get; set; }
public string ItemName { get; set; }
public Decimal? Qty { get; set; }
public Decimal? Rate { get; set; }
public Decimal? Amount { get; set; }
}
public class OrderModel
{
public string OrderNumber { get; set; }
public string OrderDate { get; set; }
public int? CustomerCode { get; set; }
public string CustomerName { get; set; }
public string Note { get; set; }
//List of items selected in Order
public List<OrderItemsModel> ItemsSelected { get; set; }
}
Extract from My View
#model OrderApplication.Models.OrderModel
#{
ViewBag.Title = "Index";
Model.ItemsSelected = ViewBag.getlist;
}
#using (Ajax.BeginForm("UpdateItemList", "Order", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "selectedtable" }))
{
<h2 style="margin-left:5%;">Order Entry</h2>
//Order No & Date
<div class="row">
<div class="col-sm-6">
<div class="col-sm-3">
#Html.LabelFor(model => model.OrderNumber, "OrderNo"):
</div>
<div class="col-sm-3">
#Html.TextBoxFor(model => model.OrderNumber, new { #class = "form-control", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="col-sm-3">
#Html.LabelFor(model => model.OrderDate, "Date"):
</div>
<div class="col-sm-3">
#Html.TextBoxFor(model => model.OrderDate, new { #class = "form-control" })
</div>
</div>
</div>
<br />
//Table of entries
<div id="selectedtable">
#Html.Partial("_selectTable", Model);
</div>
<br />
}
#*Main Save*#
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3">
#using (Html.BeginForm("SaveData", "Order", new { order = Model, id = "loginform", #class = "justify-content-center" }))
{
<input type="submit" value="Save Order" class="btn btn-success" />
}
</div>
<div class="col-sm-3">
<input type="button" class="btn btn-success" value="Clear Form" onclick="location.href='#Url.Action("Clear", "Order")'" />
</div>
</div>
</div>
My Controller
public class OrderController : Controller
{
public List<OrderItemsModel> dd = new List<OrderItemsModel>() ;
[HttpPost]
public ActionResult SaveData(OrderModel order, string id)
{
if (order == null) //order is always Nothing
{
return View(order);
}
if (order.CustomerCode == 0)
{
return View(order);
}
return View(order);
}
}
}
You shouldn't use both Ajax.BeginForm and Html.BeginForm, as it won't work. Please, check this post as might be of help to decide which one you wish to choose:
https://forums.asp.net/t/1757936.aspx?When+to+use+Html+BeginForm+vs+ajax+BeginForm
If you still want to use Html.BeginForm, just move the using sentence to replace your Ajax.BeginForm at the top of the page, so the form covers all fields, and the model won't be empty.

Update kendo grid columns without page reload in ASP MVC

I have a kendo grid where user can select list of columns from grid and save the selection by giving name (i.e view name). Each saved selection (view name) will show up as drop-down above grid so that user can change grid columns whenever they want. In current implementation, whenever user selects view name from one drop-down value to other, i call action method to select that view name as current view name. Then page reloads to invoke Index' action method to retrieve current view names columns values. I am using visible attribute in grid to show and hide columns in grid.
Now i was wondering if i can update the grid columns without reloading the page when user change the view name from the dropdown.
Thanks
Sanjeev
Screenshot:
Here is my setup:
ViewModel:
namespace MvcApplicatioin.Models
{
public class EmployeeViewModel
{
public EmployeeColumns EmployeeColumns { get; set; }
public IEnumerable<SelectListItem> EmployeeViewNames { get; set; }
public long EmployeeSelectedViewId { get; set; }
}
public class EmployeeResponse
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class EmployeeColumns
{
public bool Id { get; set; }
public bool FirstName { get; set; }
public bool LastName { get; set; }
}
}
Controller:
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Index()
{
var service = new EmployeeService();
EmployeeViewModel model = new EmployeeViewModel();
long currentViewId;
//setup views and column preferences
EmployeeColumns employeeColumns = service.GetCurrentEmployeeColumnsPreferences();
model.EmployeeColumns = employeeColumns;
model.EmployeeViewNames = service.GetAllEmployeeViewNames(out currentViewId);
model.EmployeeSelectedViewId = currentViewId;
return View(model);
}
}
Razor:
#using Kendo.Mvc.UI
#{
ViewBag.Title = "Employee Info:";
}
<h3 style="margin-bottom: 10px;">Employee Info</h3>
<input id="btnSearch" type="button" value="Search" class="btn_Search" />
<div class="row">
<div class="col-sm-12">
#(Html.Kendo().Grid<MvcApplicatioin.Models.EmployeeResponse>()
.Name("GridEmployee")
.Columns(columns =>
{
columns.Bound(e => e.Id).Width("170px").Visible(Model.EmployeeColumns.Id);
columns.Bound(e => e.FirstName).Width("190px").Visible(Model.EmployeeColumns.FirstName);
columns.Bound(e => e.LastName).Width("170px").Visible(Model.EmployeeColumns.LastName);
})
.ToolBar(tools =>
{
tools.Template(#<text>
<div class="col-lg-4 col-md-5 col-sm-5 col-xs-7 pull-right" style="padding-right: 0;">
<div class="form-group" style="margin-bottom: 0;">
#Html.Label("Grid View:", new { #class = "col-sm-3 col-xs-4 control-label view" })
<div class="col-sm-7 col-xs-6" style="padding-left: 0;">
#Html.DropDownList("lstEmployeeViewNames", new SelectList(Model.EmployeeViewNames, "Value", "Text", Model.EmployeeSelectedViewId), "- Select View Name -", new { #class = "form-control", #style = "height: auto;" })
</div>
</div>
</div>
</text>);
})
.Pageable(x => x.PageSizes(new int[] { 10, 20, 50, 100 }).ButtonCount(4))
.AutoBind(false)
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.ServerOperation(false)
.Read(read => read.Action("SearchEmployee", "Employee")))
)
</div>
</div><!--//row-->
<script type="text/javascript">
$('#btnSearch').click(function (e) {
e.preventDefault(); //This prevent the submit button onclick from submitting by itself
$('#GridEmployee').data('kendoGrid').dataSource.read();
});
//Change event for Dropdown placed inside the Grid's Toolbar - To Change the view
$("#lstEmployeeViewNames").change(function (e) {
var selectedViewId = $('select#lstEmployeeViewNames option:selected').val();
if (selectedViewId == null || selectedViewId == '') {
alert("Please select the view name from the dropdown first !!");
return;
}
$.post("/Employee/SetEmployeeColumnsCurrentPreferences", { viewId: selectedViewId }, function (data) {
window.top.location.reload();
});
});
</script>
This is how I would do a search in client. I know it doesn't tell how to show and hide columns, but at least it could put you on the right track.
The trick is to manipulate $("#GridEmployee") instead of posting.
function search() {
var searchCriteria = $("#searchField").val();
var gridData = $("#GridEmployee").data("kendoGrid");
if searchCriteria != "") {
gridData.dataSource.filter({ field: "FirstName", operator: "contains", value: searchCriteria });
} else {
gridData.dataSource.filter({});
}
}

How to capture multiple checkboxes and radio buttons posted data by viewmodel ASP.Net MVC

i am new in MVC. so this is my html looks like
<form id='your-form' action='#Url.Action("Action","Controller")' method='post'>
<b>Gender</b><br />
<input type='radio' name='gender' value='Male' /> Male <br />
<input type='radio' name='gender' value='Female' /> Female <br />
<hr />
<b>Hobbies</b><br />
<input type='checkbox' name='hobbies' value='Reading' /> Reading <br />
<input type='checkbox' name='hobbies' value='Sports' /> Sports <br />
<input type='checkbox' name='hobbies' value='Movies' /> Movies <br />
<input type='submit' value='Update Profile' />
</form>
this way i am capturing data
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string gender, string[] hobbies)
{
// Example output
var output = String.Format("The user's gender is <b>{0}</b> and they enjoy <b>{1}</b>", gender, String.Join(",", hobbies));
return Content(output);
}
}
but i like to know how could i capture it by viewmodel concept. anyone can help me with sample code. thanks
View models
public class HobbyVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class PersonVM
{
....
public string Gender { get; set; } // would be better to use an enum
public List<HobbyVM> Hobbies { get; set; }
}
In the GET method, initialize an instance of the view model and pass it to the view
public ActionResult Create()
{
PersonVM model = new PersonVM()
{
Hobbies = new List<HobbyVM>()
{
new HobbyVM(){ ID = 1, Name = "Reading" },
new HobbyVM(){ ID = 2, Name = "Sports" },
....// etc these would actually be loaded from a repository
}
};
return View(model);
}
[HttpPost]
public ActionResult Create(PersonVM model)
{
// map you view model to a instance of your data model
// save and redirect
}
View
#model PersonVM
#Html.BeginForm())
{
....
<label>
#Html.RadioButtonFor(m => m.Gender, "Male", new { id = "" })
<span>Male</span>
</label>
<label>
#Html.RadioButtonFor(m => m.Gender, "Female", new { id = "" })
<span>Female</span>
</label>
for(int i = 0; i < Model.Hobbies.Count; i++)
{
#Html.HidenFor(m => m.Hobbies[i].ID)
#Html.CheckBoxFor(m => m.Hobbies[i].IsSelected)
#Html.LabelFor(m => m.Hobbies[i].IsSelected, Model.Hobbies[i].Name)
}
<input type="submit" />
}

Model is null after submit

I wonder why the ContactModel in ContactController is not filled with the values provided in the form. Where has my head exploded?
Code as is:
HomeController (where the contact form is)
public class HomeController : Controller
{
public ActionResult Index()
{
var viewModel = new HomeViewModel();
return View(viewModel);
}
}
ViewModel for Home
public class HomeViewModel
{
public ContactModel ContactModel { get; set; }
}
ContactModel to hold the values
public class ContactModel
{
[Required(ErrorMessage = "Required")]
public String Name { get; set; }
[EmailAddress]
[Required(ErrorMessage = "Required")]
public String Email { get; set; }
[Required(ErrorMessage = "Required")]
public String Message { get; set; }
}
Index View for HomeController
#model MyNameSpace.ViewModels.HomeViewModel
#using (Html.BeginForm("Send", "Contact", FormMethod.Post))
{
<div class="form-group">
#Html.LabelFor(model => model.ContactModel.Name, "Name", new { #class = "sr-only" })
#Html.TextBoxFor(model => model.ContactModel.Name, new { #class = "form-control", #placeholder = "Name" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactModel.Email, "E-mail", new { #class = "sr-only" })
#Html.TextBoxFor(model => model.ContactModel.Email, new { #class = "form-control", #placeholder = "E-mail" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactModel.Email, "Message", new { #class = "sr-only" })
#Html.TextAreaFor(model => model.ContactModel.Message, new { #class = "form-control", #placeholder = "Message" })
</div>
<p><button type="submit" class="btn btn-default">Send</button></p>
}
ContactController Send
public class ContactController : Controller
{
[HttpPost]
public ActionResult Send(ContactModel model)
{
if (ModelState.IsValid)
{
// ModelState is not valid - but why!?
return RedirectToAction("Index", "Success");
}
return RedirectToAction("Index", "Error");
}
}
For some reason on my form submit, the model provided in ContactController.Send(ContactModel model) has all null values - where is the link broken?
Your POST action should take the view model as parameter instead of your domain model:
[HttpPost]
public ActionResult Send(HomeViewModel model)
The reason for that is pretty simple - it's the way the default model binder works. Your input fields in the view are all prefixed with ContactModel.
Alternatively you could use the Bind attribute and explicitly specify that:
[HttpPost]
public ActionResult Send([Bind(Prefix = "ContactModel")] ContactModel model)

MVC4 application on handling list

This is my model class with two classes Employee and Employee list
namespace EditMultiplerecords.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Employeelist : IEnumerable<Employee>
{
public List<Employee> employee { get; set; }
public IEnumerator<Employee> GetEnumerator()
{
return employee.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return employee.GetEnumerator();
}
}
}
This is my View where i am writing code for editing using javascript
#model EditMultiplerecords.Models.Employeelist
#{
ViewBag.Title = "Homepage";
}
<link href="../../Content/StyleSheet1.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.editor input').blur(function () {
$(this).hide();
$(this).closest('p').find('label').html($(this).val()).show();
});
$('.editor label').click(function () {
$(this).hide();
$(this).closest('p').find('input').show();
});
});
</script>
#foreach (var item in Model)
{
using (Html.BeginForm())
{
<div class="editor">
<p>
#Html.HiddenFor(x => item.Id)
#Html.LabelFor(x => item.Name, item.Name)
#Html.EditorFor(x => item.Name)
<input type="submit" value="OK" />
</p>
</div>
}
#* #Html.Partial("Details", item);*#
}
And this controller class
public ActionResult Homepage()
{
Employeelist el = new Employeelist();
el.employee = new List<Employee>();
el.employee.Add(new Employee { Id = 1, Name = "Rahul" });
el.employee.Add(new Employee { Id = 2, Name = "America" });
el.employee.Add(new Employee { Id = 3, Name = "NewJersey" });
return View(el);
}
[HttpPost]
public ActionResult Homepage(Employeelist el)
{
return View(el);
}
My problem is when i edit Rahul or America or NewJersey, on Post Action iam getting an empty list with null values rather an updated list
you need to add #foreach (var item in Model) loop inside using (Html.BeginForm()) to accept modified List
using (Html.BeginForm())
{
#foreach (var item in Model)
{
<div class="editor">
<p>
#Html.HiddenFor(x => item.Id)
#Html.LabelFor(x => item.Name, item.Name)
#Html.EditorFor(x => item.Name)
</p>
</div>
}
}
<input type="submit" value="OK" />
#* #Html.Partial("Details", item);*#
-- Edit Accept formCollection
[HttpPost]
public ActionResult Homepage(FormCollection formCollection)
{
var itemid = formCollection.GetValue("item.id");
var itemname= formCollection.GetValue("item.name");
---//use values to send it back to view----
return View();
}