Jayraj Goswami

Jayraj Goswami

  • NA
  • 198
  • 12.6k

Add Update Get Country WebApi With MVC 5

Mar 1 2016 8:46 AM
public class CountryDTO
{
public int CID { get; set; }
public string CountryName { get; set; }
public IEnumerable<CountryDTO> CountryGrid { get; set; }
public CountryDTO CountryEdit { get; set; }
}


public class Country : ICountry
{
CountryDTO objCnty = new CountryDTO();
public CountryDTO SaveCountry(CountryDTO obj)
{
using (GeesemedLocalEntities DB = new GeesemedLocalEntities())
{
using (var dbContextTransaction = DB.Database.BeginTransaction())
{
try
{
DB.Configuration.ProxyCreationEnabled = false;
DB.Configuration.LazyLoadingEnabled = false;
if (obj == null)
{
throw new ArgumentNullException("item");
}
DB.InsertUpdateCountry(0, obj.CountryName);
DB.SaveChanges();
dbContextTransaction.Commit();
return obj;
}
catch (Exception)
{
dbContextTransaction.Rollback();
throw;
}

}
}
}
public bool UpdateCountry(CountryDTO obj)
{
using (GeesemedLocalEntities DB = new GeesemedLocalEntities())
{
using (var dbContextTransaction = DB.Database.BeginTransaction())
{
try
{
DB.Configuration.ProxyCreationEnabled = false;
DB.Configuration.LazyLoadingEnabled = false;
if (obj == null)
{
throw new ArgumentNullException("item");
}
DB.InsertUpdateCountry(obj.CID, obj.CountryName);
DB.SaveChanges();
dbContextTransaction.Commit();
return true;
}
catch (Exception)
{
dbContextTransaction.Rollback();
throw;
}

}
}
}

public IEnumerable<CountryDTO> GetAll()
{
using (GeesemedLocalEntities DB = new GeesemedLocalEntities())
{
DB.Configuration.ProxyCreationEnabled = false;
DB.Configuration.LazyLoadingEnabled = false;
var CountryData = ConvertObjectToData(0);
if (CountryData != null)
{
objCnty.CountryGrid = CountryData;
return CountryData;
}
return null;
}
}

public CountryDTO Get(int id)
{
using (GeesemedLocalEntities DB = new GeesemedLocalEntities())
{
DB.Configuration.ProxyCreationEnabled = false;
DB.Configuration.LazyLoadingEnabled = false;
var CountryData = ConvertObjectToData(id);
if (CountryData != null)
{
objCnty.CountryEdit = CountryData.Single();
return CountryData.Single();
}
return null;
}
}


public IEnumerable<CountryDTO> ConvertObjectToData(int id)
{
using (GeesemedLocalEntities DB = new GeesemedLocalEntities())
{
var Result = from result in DB.GetAllCountry(id).ToList()
select new CountryDTO
{
CountryName = result.CountryName,
CID = result.CID
};

return Result;
}
}
}
interface ICountry
{
CountryDTO SaveCountry(CountryDTO obj);
bool UpdateCountry(CountryDTO obj);
IEnumerable<CountryDTO> GetAll();
CountryDTO Get(int id);
}

API Controller

[RoutePrefix("api/CountryApi")]
public class CountryApiController : ApiController
{
static readonly ICountry Counobj = new Country();
[Route("SaveCountry")]
[HttpPost]
public HttpResponseMessage SaveCountry(CountryDTO obj)
{
obj = Counobj.SaveCountry(obj);
var Responce = Request.CreateResponse<CountryDTO>(HttpStatusCode.Created, obj);
return Responce;
}
[Route("UpdateCountry")]
[HttpPut]
public HttpResponseMessage UpdateCountry(CountryDTO obj)
{
if (!Counobj.UpdateCountry(obj))
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Sorry");
}
else
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.ReasonPhrase = Convert.ToString(obj.CID); // Return the output Id of the procedure in response.
return response;
}
}

[Route("GetCountry")]
public IEnumerable<CountryDTO> GetCountry()
{
return Counobj.GetAll();
}

[Route("GetCountry/{id}")]
public HttpResponseMessage GetCountry(int id)
{
CountryDTO ObjCon = Counobj.Get(id);
if (ObjCon == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Sorry");
}
else
{
return Request.CreateResponse<CountryDTO>(ObjCon);
}
}
}


MVC


// GET: CountryApi
public ActionResult Country(int? id)
{
return View(Edit(id));
}


public CountryDTO Edit(int? id)
{
try
{
var client = new HttpClient();
var modelGrid = client.GetAsync("http://localhost:6198/api/CountryApi/GetCountry").Result
.Content.ReadAsAsync<List<CountryDTO>>().Result;
if (id != null && id != 0)
{
var modelEdit = client.GetAsync("http://localhost:6198/api/CountryApi/GetCountry/" + id).Result
.Content.ReadAsStringAsync().Result;
var ss = JsonConvert.DeserializeObject<CountryDTO>(modelEdit);
var model = new CountryDTO()
{
CountryGrid = modelGrid.OrderByDescending(item => item.CID),
CountryEdit = ss
};
return model;
}
else
{
var model = new CountryDTO()
{
CountryGrid = modelGrid.OrderByDescending(item => item.CID),
CountryEdit = null
};
return model;
}
}
catch (Exception ex)
{
throw ex;
}
}

public ActionResult Save(CountryDTO ObjCt)
{
try
{
var client = new HttpClient();
if (ObjCt.CountryEdit.CID == 0)
{

var response = client.PostAsJsonAsync("http://localhost:6198/api/CountryApi/SaveCountry", ObjCt.CountryEdit).Result;
if (response.IsSuccessStatusCode)
{


}
return RedirectToAction("Country");
}
else
{

var response = client.PutAsJsonAsync("http://localhost:6198/api/CountryApi/UpdateCountry", ObjCt.CountryEdit).Result;
if (response.IsSuccessStatusCode)
{

}
return RedirectToAction("Country");
}
}
catch (Exception ex)
{
throw ex;
}
}
}



VIEW

@model SampleMapper.CountryDTO
@{
ViewBag.Title = "Country";
}

<h2>Country</h2>

@using (Html.BeginForm())
{
@Html.Partial("AddCountryPartial", Model)
<br />
@Html.Partial("GetCountryPartial", Model)
}

@model SampleMapper.CountryDTO
<table>
<tr>
<td>
@Html.HiddenFor(item => item.CountryEdit.CID)

</td>
<td></td>

</tr>
<tr>
<td>Country Name :-</td>
<td>
@Html.TextBoxFor(item => item.CountryEdit.CountryName, new { @placeholder = "Country Name", @class = "form-control SpeCharNot", id = "txtCountry", @autocomplete = "off" })
</td>
</tr>
<tr>
<td colspan="2">
<input id="save" type="submit" value="Save" class="btn button" formaction="~/Country/Save" />
</td>

</tr>
</table>



@model SampleMapper.CountryDTO
@{
WebGrid grid = new WebGrid(Model.CountryGrid, rowsPerPage: 5, ajaxUpdateContainerId: "CountryGrid");
}

@grid.GetHtml(
htmlAttributes: new { id = "CountryGrid" },
tableStyle: "table",
mode: WebGridPagerModes.All,
firstText: "<< ",
previousText: "< ",
nextText: " >",
lastText: " >>",
columns: new[]
{
grid.Column("CountryName","Country Name"),
// grid.Column("ModuleVer","Module Ver",canSort:false), //the model fields to display
// grid.Column("Active","Active",canSort:false),
// grid.Column("Created Date",format: item => ((item.Created_Date == null) ? "" : item.Created_Date.ToString("MM/dd/yyyy")),canSort:false),
grid.Column("Action", format: @<text> @Html.ActionLink("Edit", "Country", new { id = item.CID })</text>, style: "col3Width" , canSort: false)
}
)





Answers (1)