Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Wednesday, 12 October 2016

Bind Dropdown in different ways in MVC

In MVC, drop down can be bind in different ways. Such as using ViewBag, Selectlist, Directly bind on the view etc. Following are some way through which we can bind drop down in MVC.

View (BindAllDropdown.cshtml)

@model MvcAccMgmt.Models.DropdownModel
@{
    ViewBag.Title = "BindAllDropdown";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Bind Dropdown in different way</h2>

@using (Html.BeginForm("Index", "Ajax", FormMethod.Post))
{
    <div ng-app="" ng-controller="ajaxCntr" style="height:400px; width:500px;">
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <strong>Dropdown bind on view directly  </strong>
                    @Html.DropDownList("ddlBindeInView", new List<SelectListItem>
                                        { new SelectListItem { Text = "Bhimsen", Value

= "1", Selected=true},
                                          new SelectListItem { Text = "Shiv", Value =

"2"},
                                          new SelectListItem { Text = "Ankur", Value =

"3"},
                                          new SelectListItem { Text = "Ravi", Value =

"4"}
                                        }, "Select Mobile", new { @class = "form-

control" })
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <strong>DropDownListFor (Strongly type)  </strong>
                    @Html.DropDownListFor(M => Model.ddlBindBySelectList, new

SelectList(Model.ddlStudentList, "Value", "Text"), new { @class = "form-control" })
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <strong>DropDownList by model  </strong>
                    @Html.DropDownList("ddlmob", Model.ddlStudentList, "Select Model",

new { @class = "form-control" })
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <strong>DropDownList by ViewBag  </strong>
                    @Html.DropDownList("ddlBindByViewBag", ViewBag.UserList as

SelectList, new { @class = "form-control" })

                </div>
            </div>
            <div>
            </div>

        </div>

        <div class="row">
            <div class="col-md-6">
                <strong>DropDownList Option Group  </strong>
                <div class="form-group">
                    @Html.DropDownList("ddlBindByOptGroup", ViewBag.ddlStudentListGrp

as SelectList, new { @class = "form-control" })
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <input type="submit" class="btn btn-primary" />
                </div>
            </div>
            <div>
            </div>

        </div>

    </div>
}


Controller's Action and function

  public ActionResult BindAllDropdown()
        {
            DropdownModel model = new DropdownModel();        
            model.CountryList = BindCountry();
            model.ddlStudentList = new SelectList(BindStudentList(), "Id",

"StudentName");        
            ViewBag.ddlStudentListGrp = new SelectList(BindStudentList(), "Id",

"StudentName", "StudentAddress", 1);
            ViewBag.UserList = new SelectList(BindStudentList(), "Id", "StudentName");

         
            return View(model);
         
        }

 private List<StudentModel> BindStudentList()
        {
            //IQuickQuoteOperation quoteOperation = new QuickQuoteOperation();
            using (TestDBEntities db = new TestDBEntities())
            {
                var lst = db.tbl_Student.ToList();

                List<StudentModel> lstModel = new List<StudentModel>();
                Mapper.Initialize(x => x.CreateMap<tbl_Student, StudentModel>());
                var d = Mapper.Map<IEnumerable<tbl_Student>, List<StudentModel>>(lst);
                return d.ToList();
            }

        }

 public List<Country> BindCountry()
        {
            List<Country> _objcountry = new List<Country>();
            _objcountry.Add(new Country { countryId = 1, CountryName = "India" });
            _objcountry.Add(new Country { countryId = 2, CountryName = "Pakistan" });
            _objcountry.Add(new Country { countryId = 4, CountryName = "Sri Lanka" });
            _objcountry.Add(new Country { countryId = 5, CountryName = "Japan" });
            _objcountry.Add(new Country { countryId = 6, CountryName = "China" });
            return _objcountry;
        }


Model

 public class DropdownModel
    {    
        public SelectList ddlStudentList { get; set; }
        public SelectList ddlStudentListGrp { get; set; }
        public string ddlBindBySelectList { get; set; }
        public List<Country> CountryList { get; set; }
    }


    public class Country
    {
        public int countryId { get; set; }
        public bool CheckedStatus { get; set; }
        public string CountryName { get; set; }
    }


Thursday, 11 August 2016

XML CRUD (Create Read Update Delete) Operation Using MVC

This article includes step by step tutorial to learn CRUD operation in XML file using MVC in Visual Studio.
Step 1. Creating an MVC Application
  • Open Visual Studio
  • File New Project…
  • Select ASP.NET MVC3/4 Web Application.
  • Enter the name of application as "CodeFirstDemo".
  • Click on  OK.

Step 2. Creating the Model
Right Click on the Models folder and Create a model with the name of "ProjectModels" as below the picture and Create a properties as below code


ProjectModels.cs

namespace MvcXML.Models
{
public class ProjectModels
{


public int Id { get; set; }

[Required]
public string ProjectName { get; set; }

[Required]
public string Location { get; set; }

public bool IsEdit { get; set; }
}
}
Step 3. Create a XML File
Create a Folder with the Name of XML as in following picture. and create an XML file with the name of "ProjectList.XML" using Add New Item with right click on XML folder. And Write the code as follows in XML file.
ProjectList.xml

<?xml version="1.0" encoding="utf-8"?>
<Projects>
<Project>
<Id>1</Id>
<ProjectName>The Primus</ProjectName>
<Location>Gurgaon</Location>
</Project>
<Project>
<Id>2</Id>
<ProjectName>DLF</ProjectName>
<Location>Gudgoan</Location>
</Project>
<Project>
<Id>4</Id>
<ProjectName>Dev Builders</ProjectName>
<Location>Grater Noida</Location>
</Project>
</Projects>



Step 4 : Create a Controller.
Right click on the Controller folder and create a controller with the name of "AdminController" as in picture below. And Write the following Code in as follows in Admincontroller within Index Action.






AdminController.cs

public class AdminController : Controller
{
//
// GET: /Admin/

public ActionResult Index()
{
List<ProjectModels> lstProject = new List<ProjectModels>();
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/XML/ProjectList.xml"));
DataView dvPrograms;
dvPrograms = ds.Tables[0].DefaultView;
dvPrograms.Sort = "Id";

foreach (DataRowView dr in dvPrograms)
{
ProjectModels model = new ProjectModels();
model.Id = Convert.ToInt32(dr[0]);
model.ProjectName = Convert.ToString(dr[1]);
model.Location = Convert.ToString(dr[2]);
lstProject.Add(model);
}
if (lstProject.Count > 0)
{
return View(lstProject);
}
return View();



return View();
}
ProjectModels model = new ProjectModels();
public ActionResult AddEditProject(int? id )
{

int Id = Convert.ToInt32(id);
if (Id > 0)
{
GetDetailsById(Id);
model.IsEdit = true;
return View(model);
}
else
{
model.IsEdit = false;
return View(model);
}
}

[HttpPost]
public ActionResult AddEditProject(ProjectModels mdl)
{


if (mdl.Id > 0)
{
XDocument xmlDoc = XDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));
var items = (from item in xmlDoc.Descendants("Project")
select item).ToList();
XElement selected = items.Where(p => p.Element("Id").Value == mdl.Id.ToString()).FirstOrDefault();


selected.Remove();
xmlDoc.Save(Server.MapPath("~/XML/ProjectList.xml"));
xmlDoc.Element("Projects").Add(new XElement("Project",
new XElement("Id", mdl.Id),
new XElement("ProjectName", mdl.ProjectName),
new XElement("Location", mdl.Location)

)
);
xmlDoc.Save(Server.MapPath("~/XML/ProjectList.xml"));
return RedirectToAction("Index", "Admin");
}
else
{
XmlDocument oXmlDocument = new XmlDocument();
oXmlDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));
XmlNodeList nodelist = oXmlDocument.GetElementsByTagName("Project");
var x = oXmlDocument.GetElementsByTagName("Id");
int Max = 0;
foreach (XmlElement item in x)
{
int EId = Convert.ToInt32(item.InnerText.ToString());
if (EId > Max)
{
Max = EId;
}
}
Max = Max + 1;
XDocument xmlDoc = XDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));
xmlDoc.Element("Projects").Add(new XElement("Project",
new XElement("Id", Max),
new XElement("ProjectName", mdl.ProjectName),
new XElement("Location", mdl.Location)
)
);
xmlDoc.Save(Server.MapPath("~/XML/ProjectList.xml"));
return RedirectToAction("Index", "Admin");
}
}



public ActionResult Delete(int Id)
{
if (Id > 0)
{
XDocument xmlDoc = XDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));
var items = (from item in xmlDoc.Descendants("Project")
select item).ToList();
XElement selected = items.Where(p => p.Element("Id").Value == Id.ToString()).FirstOrDefault();
selected.Remove();
xmlDoc.Save(Server.MapPath("~/XML/ProjectList.xml"));
}

return RedirectToAction("Index", "Admin");
}


public void GetDetailsById(int Id)
{
XDocument oXmlDocument = XDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));
var items = (from item in oXmlDocument.Descendants("Project")
where Convert.ToInt32(item.Element("Id").Value) == Id
select new projectItems
{
Id = Convert.ToInt32(item.Element("Id").Value),
ProjectName = item.Element("ProjectName").Value,
Location = item.Element("Location").Value,

}).SingleOrDefault();

if (items != null)
{
model.Id = items.Id;
model.ProjectName = items.ProjectName;
model.Location = items.Location;
}
}

public class projectItems
{
public int Id { get; set; }
public string ProjectName { get; set; }
public string Location { get; set; }
public projectItems()
{
}
}
}
No, Create a View for that action using right Click on the controller's action. and write the code as follows for the Index and AddEditProject respectively.
Index.cshtml file.
@model IEnumerable <MvcXML.Models.ProjectModels>
@{
ViewBag.Title = "Index";
}


<style type="text/css">
.topDiv
{
width: 50%;
margin: 10px auto;
background-color: #f2f2f2;
text-align: left;
padding: 2%;
}
</style>

<div class="topDiv">
<fieldset style="margin: 2% auto; width: 90%; background-color: #FFEBCD; text-align: center">
<h4>
@Html.ActionLink("Add New project", "AddEditProject")
</h4>
</fieldset>
<fieldset>
<table style="margin: 2% auto; padding: 5px; width: 90%">
<tr style="background-color: #FFFACD">
<th>
ProjectName
</th>
<th>
Location
</th>
<th>
Manage
</th>
</tr>

@{
foreach (var item in Model)
{
<tr style="background-color: #FFFFF0">
<td>
@item.ProjectName
</td>
<td>
@item.Location
</td>
<td>
@Html.ActionLink("Edit", "AddEditProject", new { id = @item.Id }) / @Html.ActionLink("Delete", "Delete", new { id = @item.Id })
@* /@Html.ActionLink("Details", "ProjectDetails", new { basePath = @item.basePath })*@
</td>
</tr>
}
}

</table>
</fieldset>
</div>


Now, Again go to AdminController and create new view for AddEditProject action with right click and write the following code.

AddEditProject.cshtml
@model MvcXML.Models.ProjectModels
@{
ViewBag.Title = "AddEditProject";
}

<style type="text/css">
.topDiv
{
width: 50%;
margin: 10px auto;
background-color: #f2f2f2;
text-align: center;
padding: 2%;
}
.innerDiv
{
margin: 0 auto;
padding: 1%;
color: Gray;
}
</style>

@using (Html.BeginForm())
{
<div class="topDiv">
<table>
<tr> <h2>Add/Edit User</h2></tr>

<tr>
<td>
@Html.LabelFor(m => m.ProjectName) :
</td>
<td>
<div class="innerDiv">
@Html.TextBoxFor(m => m.ProjectName)
@Html.ValidationMessageFor(m => m.ProjectName)
</div>
</td>
</tr>
<tr>
<td>
@Html.LabelFor(m => m.Location) :
</td>
<td>
<div class="innerDiv">
@Html.TextBoxFor(m => m.Location)
@Html.ValidationMessageFor(m => m.ProjectName)
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="innerDiv">
<input id="btnAdd" type="submit" value="@if (Model.IsEdit)
{<text>Update</text>}
else
{<text>Add</text>}" style=" width:75px" />
</div>
</td>
</tr>
</table>
</div>
}


Now press F5 to run the application,


Hope your browser will be like following screen.
and after clicking on Add New Project and Edit link your view will be like following.




Summary
In this walkthrough we looked the development for XML CRUD operation using a MVC. We defined a XML Class and use that class for CRUD operation.

Thank You