The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'Int32' for method 'Edit(Int32)' - asp.net-mvc

I am performing CRUD operation using linq to sql. But while clicking on Edit, Details or delete it gives me error i.e. "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'CRUD_using_LinQ_to_SQL_in_MVC.Controllers.OTDController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
I checked the solution and found that, while running application url didn't get ID parameter. But i dont understand what should i change in my code.. Can you please help me...
My Controller Code:
using System;
namespace CRUD_using_LinQ_to_SQL_in_MVC.Controllers
{
public class OTDController : Controller
{
private IOTddataRepository repository;
public OTDController()
: this(new OtdDataRepository())
{
}
public OTDController(IOTddataRepository _repository)
{
repository = _repository;
}
//-----------------------Index--------------------------
public ActionResult Index()
{
var otddata = repository.Getallotddata();
return View(otddata);
}
//-----------------------Details--------------------------
public ActionResult Details(int id)
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
//-----------------------Create--------------------------
public ActionResult Create()
{
return View(new OtdModelClass());
}
[HttpPost]
public ActionResult Create(OtdModelClass otdmodel)
{
try
{
if (ModelState.IsValid)
{
repository.Insertotddata(otdmodel);
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Problem in Data Saving");
}
return View(otdmodel);
}
//-----------------------EDIT--------------------------
public ActionResult Edit(int id)
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
[HttpPost]
public ActionResult Edit(OtdModelClass otdclass)
{
try
{
if (ModelState.IsValid)
{
repository.Updateotddata(otdclass);
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Problem in editing and Updating data");
}
return View(otdclass);
}
//-----------------------Delete--------------------------
public ActionResult Delete(int id, bool? savechangeserror)
{
if (savechangeserror.GetValueOrDefault())
{
ViewBag.ErrorMessage = "Problem in Deleting";
}
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
try
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
repository.Deleteotddata(id);
}
catch (DataException)
{
return RedirectToAction("Delete", new System.Web.Routing.RouteValueDictionary {
{"id",id},
{"SaveChangesError",true}});
}
return RedirectToAction("Index");
}
}
}
My OTD class Code:
public class OtdDataRepository : IOTddataRepository
{
private MVCLoginMasterLogDataClassesDataContext otdcontextobj;
public OtdDataRepository()
{
otdcontextobj = new MVCLoginMasterLogDataClassesDataContext();
}
public IEnumerable<OtdModelClass> Getallotddata()
{
IList<OtdModelClass> otddatalist = new List<OtdModelClass>();
var myselectallquery = from otduser in otdcontextobj.tbl_MVC_Login_Master_Logs select otduser;
var otd = myselectallquery.ToList();
foreach (var otddata in otd)
{
otddatalist.Add(new OtdModelClass()
{
Srno=Convert.ToInt32(otddata.Srno),
MemberCode = otddata.MemberCode,
LoginID = otddata.LoginID,
OTDPassword = otddata.OTDPassword,
BBSID = otddata.BBSID,
IPAddress = otddata.IPAddress,
ServerType = otddata.ServerType,
OTDStatus = otddata.OTDStatus,
RemoteIP = otddata.RemoteIP,
RemotePort = otddata.RemotePort,
AllowDownload = otddata.AllowDownload,
OTDTimeStamp = otddata.OTDTimeStamp,
MemberType = otddata.MemberType,
EQ = otddata.EQ,
EQD = otddata.EQD,
BFX = otddata.BFX,
SLB = otddata.SLB,
Others = otddata.Others
});
}
return otddatalist;
}
public OtdModelClass Getotddatabysrno(int id)
{
var getotddataquery = from otduser in otdcontextobj.tbl_MVC_Login_Master_Logs
where otduser.Srno == id
select otduser;
var otddata = getotddataquery.FirstOrDefault();
var otdmodel = new OtdModelClass()
{
Srno = Convert.ToInt32(otddata.Srno),
MemberCode = otddata.MemberCode,
LoginID = otddata.LoginID,
OTDPassword = otddata.OTDPassword,
BBSID = otddata.BBSID,
IPAddress = otddata.IPAddress,
ServerType = otddata.ServerType,
OTDStatus = otddata.OTDStatus,
RemoteIP = otddata.RemoteIP,
RemotePort = otddata.RemotePort,
AllowDownload = otddata.AllowDownload,
OTDTimeStamp = otddata.OTDTimeStamp,
MemberType = otddata.MemberType,
EQ = otddata.EQ,
EQD = otddata.EQD,
BFX = otddata.BFX,
SLB = otddata.SLB,
Others = otddata.Others
};
return otdmodel;
}
public void Insertotddata(OtdModelClass otdmodel_obj)
{
var empdata = new tbl_MVC_Login_Master_Log()
{
Srno = Convert.ToInt32(otdmodel_obj.Srno),
MemberCode = otdmodel_obj.MemberCode,
LoginID = otdmodel_obj.LoginID,
OTDPassword = otdmodel_obj.OTDPassword,
BBSID = otdmodel_obj.BBSID,
IPAddress = otdmodel_obj.IPAddress,
ServerType = otdmodel_obj.ServerType,
OTDStatus = otdmodel_obj.OTDStatus,
RemoteIP = otdmodel_obj.RemoteIP,
RemotePort = otdmodel_obj.RemotePort,
AllowDownload = otdmodel_obj.AllowDownload,
OTDTimeStamp = otdmodel_obj.OTDTimeStamp,
MemberType = otdmodel_obj.MemberType,
EQ = otdmodel_obj.EQ,
EQD = otdmodel_obj.EQD,
BFX = otdmodel_obj.BFX,
SLB = otdmodel_obj.SLB,
Others = otdmodel_obj.Others
};
otdcontextobj.tbl_MVC_Login_Master_Logs.InsertOnSubmit(empdata);
otdcontextobj.SubmitChanges();
}
public void Deleteotddata(int id)
{
tbl_MVC_Login_Master_Log otd_deletelog = otdcontextobj.tbl_MVC_Login_Master_Logs.Where(otduser => otduser.Srno == id).SingleOrDefault();
otdcontextobj.tbl_MVC_Login_Master_Logs.DeleteOnSubmit(otd_deletelog);
otdcontextobj.SubmitChanges();
}
public void Updateotddata(OtdModelClass otdmodel_obj)
{
tbl_MVC_Login_Master_Log otd_updatelog = otdcontextobj.tbl_MVC_Login_Master_Logs.Where(otduser=>otduser.Srno==otdmodel_obj.Srno).SingleOrDefault();
otd_updatelog.Srno = otdmodel_obj.Srno;
otd_updatelog.MemberCode = otdmodel_obj.MemberCode;
otd_updatelog.LoginID = otdmodel_obj.LoginID;
otd_updatelog.OTDPassword = otdmodel_obj.OTDPassword;
otd_updatelog.BBSID = otdmodel_obj.BBSID;
otd_updatelog.IPAddress = otdmodel_obj.IPAddress;
otd_updatelog.ServerType = otdmodel_obj.ServerType;
otd_updatelog.OTDStatus = otdmodel_obj.OTDStatus;
otd_updatelog.RemoteIP = otdmodel_obj.RemoteIP;
otd_updatelog.RemotePort = otdmodel_obj.RemotePort;
otd_updatelog.AllowDownload = otdmodel_obj.AllowDownload;
otd_updatelog.OTDTimeStamp = otdmodel_obj.OTDTimeStamp;
otd_updatelog.MemberType = otdmodel_obj.MemberType;
otd_updatelog.EQ = otdmodel_obj.EQ;
otd_updatelog.EQD = otdmodel_obj.EQD;
otd_updatelog.BFX = otdmodel_obj.BFX;
otd_updatelog.SLB = otdmodel_obj.SLB;
otd_updatelog.Others = otdmodel_obj.Others;
otdcontextobj.SubmitChanges();
}
}
Can you please help me...

The framework is telling you that the link you are clicking on to call the Edit and Delete action methods is not providing an int parameter named id which the action method is expecting to find somewhere in the submitted data. This is usually provided either in the URL, query string or submitted variables.
If that is not enough for you to spot the problem, post your view code specially the section related to the links.

Related

WCF---Consuming CRUD operation using Linq in ASP.NET MVC application?

enter image description here
First step...Opened WCF created IService:
namespace CRUDOperationWCFMVC
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
bool CreateDetails(EmployeeDetails employeeDetails);
[OperationContract]
bool UpdateDetails(EmployeeDetails employeeDetails);
[OperationContract]
bool DeleteDetails(int id);
[OperationContract]
List<EmployeeDetails> GetDetails();
}
public class EmployeeDetails
{
[DataMember]
public int EmpID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Location { get; set; }
[DataMember]
public int? Salary { get; set; }
}
}
Step 2: then I implemented service code:
public class Service1 : IService1
{
DataClasses1DataContext dcd = new DataClasses1DataContext();
public bool CreateDetails(EmployeeDetails employeeDetails)
{
Nevint emp = new Nevint();
emp.EmpID= employeeDetails.EmpID;
emp.Name = employeeDetails.Name;
emp.Location = employeeDetails.Location;
emp.Salary = employeeDetails.Salary;
dcd.Nevints.InsertOnSubmit(emp);
dcd.SubmitChanges();
return true;
}
public bool DeleteDetails(int id)
{
var delete = (from v in dcd.Nevints where v.EmpID==id select v).FirstOrDefault();
dcd.Nevints.DeleteOnSubmit(delete);
dcd.SubmitChanges();
return true;
}
public List<EmployeeDetails> GetDetails()
{
List<EmployeeDetails> details = new List<EmployeeDetails>();
var select= (from v in dcd.Nevints select v);
foreach (var i in select)
{
EmployeeDetails emp = new EmployeeDetails();
emp.EmpID = i.EmpID;
emp.Name = i.Name;
emp.Location = i.Location;
emp.Salary = i.Salary;
details.Add(emp);
}
return details;
}
public bool UpdateDetails(EmployeeDetails employeeDetails)
{
var update = (from v in dcd.Nevints.ToList() where employeeDetails.EmpID==v.EmpID select v).FirstOrDefault();
update.EmpID = employeeDetails.EmpID;
update.Name = employeeDetails.Name;
update.Location = employeeDetails.Location;
update.Salary = employeeDetails.Salary;
dcd.SubmitChanges();
return true;
}
}
Step 3: then I add linq to sql, opened my ASP.NET MVC project for consuming, and added a controller and wrote this code:
namespace ConsumingClient.Controllers
{
public class EmpdetailsController : Controller
{
ServiceReference1.Service1Client serobj=new ServiceReference1.Service1Client();
ServiceReference1.EmployeeDetails empdetails=new ServiceReference1.EmployeeDetails();
// GET: Empdetails
public ActionResult Index()
{
List<employee> lstemp = new List<employee>();
var result = serobj.GetDetails();
foreach (var i in result)
{
employee emp = new employee();
empdetails.EmpID = i.EmpID;
empdetails.Name = i.Name;
empdetails.Location = i.Location;
empdetails.Salary = i.Salary;
lstemp.Add(emp);
}
return View(result);
}
// GET: Empdetails/Details/5
public ActionResult Details(int id)
{
Employees emp = new Employees();
return View();
}
// GET: Empdetails/Create
public ActionResult Create()
{
return View();
}
// POST: Empdetails/Create
[HttpPost]
public ActionResult Create(Employees employees)
{
try
{
// TODO: Add insert logic here
empdetails.EmpID=employees.EmpID;
empdetails.Name = employees.Name;
empdetails.Location = employees.Location;
empdetails.Salary = employees.Salary;
serobj.CreateDetails(empdetails);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Empdetails/Edit/5
public ActionResult Edit(int id)
{
Employees emp = new Employees();
var result = serobj.GetDetails().FirstOrDefault(a=>a.EmpID==id);
emp.EmpID = result.EmpID;
emp.Name = result.Name;
emp.Location = result.Location;
emp.Salary = result.Salary;
return View(emp);
}
// POST: Empdetails/Edit/5
[HttpPost]
public ActionResult Edit(Employees employees)
{
try
{
// TODO: Add update logic here
empdetails.EmpID = employees.EmpID;
empdetails.Name = employees.Name;
empdetails.Location = employees.Location;
empdetails.Salary = employees.Salary;
serobj.UpdateDetails(empdetails);
return RedirectToAction("Index");
}
catch
{
return View(employees);
}
}
// GET: Empdetails/Delete/5
public ActionResult Delete(int id)
{
Employees emp = new Employees();
var result = serobj.GetDetails().FirstOrDefault(a=>a.EmpID==id);
emp.EmpID = result.EmpID;
emp.Name = result.Name;
emp.Location = result.Location;
emp.Salary = result.Salary;
return View(emp);
}
// POST: Empdetails/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
serobj.DeleteDetails(id);
return RedirectToAction("Index");
}
catch
{
return View(id);
}
}
}
}
Data was displaying fine. I can create data.
However, when I click on edit and delete, I'm getting an error:
ERROR Message "Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'ConsumingClient.Controllers.EmpdetailsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
This error is thrown if you attempt to call this controller action and you do not specify the id either in the path portion or as query string parameter. Since your controller action takes an id as parameter you should make sure that you always specify this parameter.
Make sure that when you are requesting this action you have specified a valid id in the url:
http://example.com/somecontroller/Edit/123
If you are generating an anchor, make sure there's an id:
#Html.ActionLink("Edit", "somecontroller", new { id = "123" })
If you are sending an AJAX request, also make sure that the id is present in the url.
If on the other hand the parameter is optional, you could make it a nullable integer:
public ActionResult Edit(int? id)
but in this case you will have to handle the case where the parameter value is not specified.
https://coderedirect.com/questions/197477/mvc-the-parameters-dictionary-contains-a-null-entry-for-parameter-k-of-non-n

How do I programmatically add records to an Umbraco v8 form?

I'm looking to add records to an Umbraco v8 form. I know I need the form guid. Is this how I'd do it? Something like this?
public void PostFormData()
{
Guid FormGuid = new Guid("8494a8f0-94da-490e-bd61-7e658c226142");
var form = _formService.Get(FormGuid);
//place for field data into fieldDic
var fieldDic = new Dictionary<Guid, RecordField>();
var firstName = form.AllFields.First(f => f.Alias == "firstName");
var firstNameRecord = new RecordField(firstName);
firstNameRecord.Values = new List<object>() { "Mad Max" };
fieldDic.Add(firstName.Id, firstNameRecord);
var record = new Record()
{
Created = DateTime.Now,
Form = form.Id,
RecordFields = fieldDic,
State = FormState.Submitted,
};
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
}
Here's how I do it. Note, I'm hard-coding the Record.UmbracoPageId to -1 while you might want to actually pass in the correct page ID.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Forms.Core.Data.Storage;
using Umbraco.Forms.Core.Models;
using Umbraco.Forms.Core.Persistence.Dtos;
using Umbraco.Forms.Core.Services;
namespace myProject.Services
{
public class FormServiceComposer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<IFormService, FormService>(Lifetime.Request);
}
}
public interface IFormService
{
void InsertFormData(Guid formGuid, object formModel, string ipAddress);
}
public class FormService : IFormService
{
private readonly ILogger _logger;
private readonly Umbraco.Forms.Core.Services.IFormService _formService;
private readonly IRecordStorage _recordStorage;
private readonly IRecordFieldStorage _recordFieldStorage;
private readonly IWorkflowService _workflowService;
public FormService(ILogger logger, Umbraco.Forms.Core.Services.IFormService formService, IRecordStorage recordStorage, IRecordFieldStorage recordFieldStorage, IWorkflowService workflowService)
{
_logger = logger;
_formService = formService;
_recordStorage = recordStorage;
_recordFieldStorage = recordFieldStorage;
_workflowService = workflowService;
}
#region IFormService
public void InsertFormData(Guid formGuid, object formModel, string ipAddress)
{
try
{
Form form = _formService.GetForm(formGuid);
Record record = new Record();
foreach (Field field in form.AllFields)
{
string caption = CleanCaption(field.Caption);
if (formModel.GetType().GetProperty(caption) == null) continue;
var propertyValue = formModel.GetType().GetProperty(caption).GetValue(formModel, null);
if (propertyValue != null)
{
List<object> values = ExtractValues(propertyValue);
RecordField recordField = new RecordField
{
Alias = field.Alias,
FieldId = field.Id,
Field = field,
Key = Guid.NewGuid(),
Record = record.Id,
Values = values
};
_recordFieldStorage.InsertRecordField(recordField);
record.RecordFields.Add(recordField.Key, recordField);
}
}
record.Form = formGuid;
record.IP = ipAddress;
record.UmbracoPageId = -1;
record.State = Umbraco.Forms.Core.Enums.FormState.Approved;
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
_recordStorage.DisposeIfDisposable();
}
catch (Exception ex)
{
_logger.Error<FormService>(ex, "Failed inserting Umbraco Forms data for {formGuid}");
}
}
#endregion IFormService
#region Private
private string CleanCaption(string caption)
{
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
return rgx.Replace(caption.Trim().Replace(" ", ""), "");
}
private List<object> ExtractValues(object propertyValue)
{
List<object> result = new List<object>();
if (propertyValue is string == false && propertyValue.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
IEnumerable<object> _propertyValue = (IEnumerable<object>)propertyValue;
if (_propertyValue.Any())
{
if (_propertyValue.First().GetType().GetProperties().Count() > 1)
{
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
string _value = string.Empty;
foreach (var _property in _propertyValue.First().GetType().GetProperties())
{
string _key = _property.Name;
_value = _value + (_value == "" ? "" : " - ") + item[_key].ToString();
}
result.Add(_value);
}
}
else
{
string _key = _propertyValue.First().GetType().GetProperties().First().Name;
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
result.Add(item[_key].ToString());
}
}
}
}
else
{
result.Add(propertyValue);
}
return result;
}
#endregion Private
}
}

i'm facing problem to access value from database of lstpresentEmp and lstAbsentEmp , on Employee controller

namespace BarrownzAdmin.Controllers
{
public class HRController : BaseController
{
EncryptionManager em = new EncryptionManager();
static string empstaticid = "";
static string rescanstaticid = "";
// GET: HR
public ActionResult Index()
{
if (Session["HRuser"] != null)
{
ViewBag.ControllerVariable = 2;
CandidateActivityIndex();
GetScheduleIV();
GetWeekIVSchedule();
GetTodaysResume();
GetWeekResume();
GetEmpUnassignTask();
BindPresentEmp();
BindAbsentEmp();
return View();
}
else
{
return RedirectToAction("Login", "Access");
}
}
[NonAction]
public void BindPresentEmp()
{
Employee em = new Employee();
MasterBusinesslayer hrLayer = new MasterBusinesslayer();
List<Employee> _lstPresentEmp = hrLayer.GetFiveEmpLeave(em.BindPresentEmpl(), em);
ViewBag.PresentEmp = _lstPresentEmp;
}
[NonAction]
public void BindAbsentEmp()
{
Employee em = new Employee();
MasterBusinesslayer hrLayer = new MasterBusinesslayer();
List<Employee> _lstAbsentEmp = hrLayer.GetFiveEmpLeave(em.BindAbsentEmpl(), em);
ViewBag.AbsentEmp = _lstAbsentEmp;
}

Check for but allow duplicates entries in the Db

My Db allows duplicate monuments, so the traditional method of checking for duplicates will not work. The user first inputs a monument name, then I run a check against the Db and if no duplicates found, great, allow the user to input the rest of the data. If one of more monuments with the same name are found, display a list of the monuments already in the Db. If this is truly a new monument with the same name, allow the user to input the new monument.
What I have so far:
[Authorize]
public ActionResult MonumentTitle(string battleRecordID, int callingRecordID)
{
ViewBag.monumentBattleRecID = battleRecordID; // ID of the battle
ViewBag.battleName = getBattleName(battleRecordID);
var vModel = new MonumentTitle();
vModel.BattleRecID = ViewBag.monumentBattleRecID;
vModel.BattleName = ViewBag.battleName;
vModel.CallingRecID = callingRecordID;
return View(vModel);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitle(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
ViewBag.battleName = monumentTitle.BattleName;
ViewBag.MonumentName = monumentTitle.MonumentName;
var NmonumentTitle = monumentTitle;
ViewBag.battleName1 = NmonumentTitle.BattleName;
var List_monument = from s in db.Monuments
where (s.MonumentStatus == "A" &&
s.MonumentBattleRecID == monumentTitle.BattleRecID &&
s.MonumentName == monumentTitle.MonumentName
)
select s;
List_monument = List_monument.OrderBy(s => s.MonumentName);
var vModel = new MonumentTitleDuplicate();
vModel.MonumentTitle = NmonumentTitle;
vModel.Monument = List_monument.ToList();
if (vModel.Monument.Count == 0)
{
return RedirectToAction("MonumentCreate", new { battleRecord = vModel.MonumentTitle.BattleRecID, callingRecordID = vModel.MonumentTitle.CallingRecID, monumentName = vModel.MonumentTitle.MonumentName });
}
{
return RedirectToAction("MonumentTitleDuplicate", vModel );
}
}
Works for when there is not a duplicate. Where I run into a problem is trying to switch control to "MonumentTitleDuplicate" and pass the model.
[Authorize]
[HttpGet]
public ViewResult MonumentTitleDuplicate(MonumentTitleDuplicate monumentTitleDuplicate)
{
return View("MonumentTitleDuplicate", monumentTitleDuplicate);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitleDuplicate(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
return RedirectToAction("MonumentCreate", new { battleRecord = monumentTitle.BattleRecID, callingRecordID = monumentTitle.CallingRecID, monumentName = monumentTitle.MonumentName });
}
[Authorize]
public ActionResult MonumentCreate(string battleRecord, int callingRecordID, string monumentName)
{
Got it -- needed to use TempData to pass the model to the new controller so:
[Authorize]
public ActionResult MonumentTitle(string battleRecordID, int callingRecordID)
{
ViewBag.monumentBattleRecID = battleRecordID; // ID of the battle
ViewBag.battleName = getBattleName(battleRecordID);
var vModel = new MonumentTitle();
vModel.BattleRecID = ViewBag.monumentBattleRecID;
vModel.BattleName = ViewBag.battleName;
vModel.CallingRecID = callingRecordID;
return View(vModel);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitle(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
ViewBag.battleName = monumentTitle.BattleName;
ViewBag.MonumentName = monumentTitle.MonumentName;
var NmonumentTitle = monumentTitle;
ViewBag.battleName1 = NmonumentTitle.BattleName;
var List_monument = from s in db.Monuments
where (s.MonumentStatus == "A" &&
s.MonumentBattleRecID == monumentTitle.BattleRecID &&
s.MonumentName == monumentTitle.MonumentName
)
select s;
List_monument = List_monument.OrderBy(s => s.MonumentName);
var vModel = new MonumentTitleDuplicate();
vModel.MonumentTitle = NmonumentTitle;
vModel.Monument = List_monument.ToList();
if (vModel.Monument.Count == 0)
{
return RedirectToAction("MonumentCreate", new { battleRecord = vModel.MonumentTitle.BattleRecID, callingRecordID = vModel.MonumentTitle.CallingRecID, monumentName = vModel.MonumentTitle.MonumentName });
}
{
TempData["monumentTitleDuplicate"] = vModel;
return RedirectToAction("MonumentTitleDuplicate");
}
}
[Authorize]
public ActionResult MonumentTitleDuplicate()
{
MonumentTitleDuplicate monumentTitleDuplicate = TempData["MonumentTitleDuplicate"] as MonumentTitleDuplicate;
return View(monumentTitleDuplicate);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitleDuplicate(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
return RedirectToAction("MonumentCreate", new { battleRecord = monumentTitle.BattleRecID, callingRecordID = monumentTitle.CallingRecID, monumentName = monumentTitle.MonumentName });
}
Probably have some cleanup work to do (like getting rid of the stuff where I was trying to use ViewBag), but does appear to be working.

Combine model in asp.net mvc

I combine my tables to Result. İt works with no problem.
public ActionResult Index()
{
var Result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return View(Result );
}
However, when using multiple actions, i have to write the above code every time.
For instance:
public ActionResult Customer()
{
var Result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return View(Result );
}
public ActionResult Product()
{
var Result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return View(Result );
}
İ have to combine my tables in every actionresult.
How can i write only one time and use my Result everywhere ?
You may do as follows. I always use this approach:
public Modeller GetResult()
{
var result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return result;
}
public ActionResult Customer()
{
var Result = GetResult();
return View(Result);
}
public ActionResult Product()
{
var Result = GetResult();
return View(Result);
}
One option is to just reference a shared class/service. For example:
public class YourService
{
public static Modeller GetCombinedTables()
{
return new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList()
};
}
}
Then, in your action you can just call that method:
public ActionResult Customer()
{
var Result = YourService.GetCombinedTables();
return View(Result);
}
You can also create the Result variable at controller level, so that way you don't have to assign it for every action.

Resources