Tag [paginate] is missing required attribute [total] in grails - grails-2.0

i have a controller ressource
package tachemanagement
import org.springframework.dao.DataIntegrityViolationException
import tachemanagement.secu.Role
class RessourceeeController {
static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
def index() {
redirect(action: "list", params: params)
}
def list(Integer max) {
params.max = Math.min(max ?: 10, 100)
[ressourceeeInstanceList: Ressourceee.list(params), ressourceeeInstanceTotal: Ressourceee.count()]
[ roleInstanceList: Role.list( params ), roleInstanceTotal: Role.count() ]
}
def create() {
[ressourceeeInstance: new Ressourceee(params)]
[roleInstance: new Role(params)]
}
def save() {
def ressourceeeInstance = new Ressourceee(params)
def roleInstance = new Role(params)
if (!ressourceeeInstance.save(flush: true)) {
render(view: "create", model: [ressourceeeInstance: ressourceeeInstance])
return
}
if (!roleInstance.save(flush: true)) {
render(view: "create", model: [roleInstance: roleInstance])
return
}
flash.message = message(code: 'default.created.message', args: [message(code: 'ressourceee.label', default: 'Ressourceee'), ressourceeeInstance.id])
redirect(action: "show", id: ressourceeeInstance.id)
flash.message = message(code: 'default.created.message', args: [message(code: 'role.label', default: 'Role'), roleInstance.id])
redirect(action: "show", id: roleInstance.id)
}
def show(Long id) {
def ressourceeeInstance = Ressourceee.get(id)
def roleInstance = Role.get(id)
if (!ressourceeeInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'ressourceee.label', default: 'Ressourceee'), id])
redirect(action: "list")
return
}
if(!roleInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'Role.label', default: 'Role'), id])
redirect(action:list)
}
[ressourceeeInstance: ressourceeeInstance]
[roleInstance: roleInstance]
}
def edit(Long id) {
def ressourceeeInstance = Ressourceee.get(id)
if (!ressourceeeInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'ressourceee.label', default: 'Ressourceee'), id])
redirect(action: "list")
return
}
[ressourceeeInstance: ressourceeeInstance]
}
def update(Long id, Long version) {
def ressourceeeInstance = Ressourceee.get(id)
if (!ressourceeeInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'ressourceee.label', default: 'Ressourceee'), id])
redirect(action: "list")
return
}
if (version != null) {
if (ressourceeeInstance.version > version) {
ressourceeeInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
[message(code: 'ressourceee.label', default: 'Ressourceee')] as Object[],
"Another user has updated this Ressourceee while you were editing")
render(view: "edit", model: [ressourceeeInstance: ressourceeeInstance])
return
}
}
ressourceeeInstance.properties = params
if (!ressourceeeInstance.save(flush: true)) {
render(view: "edit", model: [ressourceeeInstance: ressourceeeInstance])
return
}
flash.message = message(code: 'default.updated.message', args: [message(code: 'ressourceee.label', default: 'Ressourceee'), ressourceeeInstance.id])
redirect(action: "show", id: ressourceeeInstance.id)
}
def delete(Long id) {
def ressourceeeInstance = Ressourceee.get(id)
def roleInstance = Role.get(id)
if (!ressourceeeInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'ressourceee.label', default: 'Ressourceee'), id])
redirect(action: "list")
return
}
if(!roleInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'role.label', default: 'Role'), id])
redirect(action:list)
return
}
try {
ressourceeeInstance.delete(flush: true)
flash.message = message(code: 'default.deleted.message', args: [message(code: 'ressourceee.label', default: 'Ressourceee'), id])
redirect(action: "list")
}
catch (DataIntegrityViolationException e) {
flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'ressourceee.label', default: 'Ressourceee'), id])
redirect(action: "show", id: id)
}
try {
roleInstance.delete(flush: true)
flash.message = message(code: 'default.deleted.message', args: [message(code: 'role.label', default: 'Role'), id])
redirect(action: "list")
}
catch (DataIntegrityViolationException e) {
flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'role.label', default: 'Role'), id])
redirect(action: "show", id: id)
}
}
}
i hav added to my controller a code for getting id of role
but it generated a problem
URI:/tachemanagement/ressourceee/listClass:org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagExceptionMessage:Tag [paginate] is missing required attribute [total]

I think you forgot to return "total" variable. For example, in one of your controller, you should return:
render(view: "create", model: [roleInstance: roleInstance, max: your_max_variable])
your information is not very clear about which action produces this kind of error and how you input your g:pagination taglib

Related

send data to RoutingSlipCompleted consume method from activity

I have some data in activity which I want to get it in RoutingSlipCompleted consume method. I know we can send data with CompletedWithVariables from a activity to b activity. But I was wondering how it is possible to get data from activity in RoutingSlipCompleted. so this is my activity:
public class CheckInventoryActivity : IActivity<ICheckInventoryRequest, CheckInventoryRequestCompensate>
{
private readonly IInventoryService _inventoryService;
private readonly IEndpointNameFormatter _formatter;
public CheckInventoryActivity(IInventoryService inventoryService, IEndpointNameFormatter formatter)
{
_inventoryService = inventoryService;
_formatter = formatter;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ICheckInventoryRequest> context)
{
CheckInventoryRequest model = new CheckInventoryRequest()
{
PartCode = context.Arguments.PartCode
};
var response = await _inventoryService.CheckInventory(model);
var checkInventoryResponse = new CheckInventoryResponse()
{
PartCode = response.Data.PartCode ?? model.PartCode,
Id = response.Data.Id ?? 0,
InventoryCount = response.Data.InventoryCount ?? 0
};
var checkInventoryCustomActionResult = new CustomActionResult<CheckInventoryResponse>()
{
Data = checkInventoryResponse,
IsSuccess = true,
ResponseDesc = "success",
ResponseType = 0
};
var result = response.IsSuccess;
if (!result)
return context.CompletedWithVariables<CheckInventoryRequestCompensate>(
new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
}, new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
});
var queueName = _formatter.ExecuteActivity<CallSuccessActivity, ISuccessRequest>();
var uri = new Uri($"queue:{queueName}");
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so by the following line of codes I can get data in CallSuccessActivity:
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so I can get this data here:
public class CallSuccessActivity : IExecuteActivity<ISuccessRequest>
{
private readonly IRequestClient<ISuccessRequest> _requestClient;
public CallSuccessActivity(IRequestClient<ISuccessRequest> requestClient)
{
_requestClient = requestClient;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ISuccessRequest> context)
{
var iModel = context.Arguments;
var model = new SuccessRequest()
{
LogDate = iModel.LogDate,
MethodName = iModel.MethodName,
CheckInventoryCustomActionResult = iModel.CheckInventoryCustomActionResult
};
//CustomActionResult< CheckInventoryResponse > CheckInventoryResponse = new ();
var rabbitResult = await _requestClient.GetResponse<CustomActionResult<SuccessResponse>>(model);
return context.Completed();
}
}
I want to get this iModel.CheckInventoryCustomActionResult in RoutingSlipCompleted :
public async Task Consume(ConsumeContext<RoutingSlipCompleted> context)
{
var requestId =
context.Message.GetVariable<Guid?>(nameof(ConsumeContext.RequestId));
var checkInventoryResponseModel = context.Message.Variables["CheckInventoryResponse"];
var responseAddress =
context.Message.GetVariable<Uri>(nameof(ConsumeContext.ResponseAddress));
var request =
context.Message.GetVariable< ICheckInventoryRequest > ("Model");
throw new NotImplementedException();
}
Instead of putting the value into the activity arguments, add it as a variable:
return context.ReviseItinerary(x =>
{
x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity"
});
x.AddVariable("CheckInventoryCustomActionResult", checkInventoryCustomActionResult);
});

nswag.json to flattenInheritanceHierarchy is not working dotnet 6

I'm trying to generate flate type script class using nswag
I belive there's a proprty 'flattenInheritanceHierarchy' that can do what i need. but seems like its not working. not sure what i'm missing.
I have a c# class called Result which is inheriting from Result
public partial record Result
{
public bool IsSucceeded { get; set; }
public string Message { get; set; } = string.Empty;
}
public partial record Result<T> : Result where T : new()
{
public T Value { get; set; } = new T();
}
i'm using it to retunr the result like this
public async Task<IActionResult> Create(CarDto dto)
{
return Ok(new Result<CarDto>());
}
when i generate typescript classes, actual result is
export class Result {
isSucceeded!: boolean;
message!: string;
}
export class ResultOfCarDto extends Result {
value!: CarDto;
}
but i want it like
export class ResultOfCarDto {
isSucceeded!: boolean;
message!: string;
value!: CarDto;
}
here's my nswag.json
{
"runtime": "Net60",
"defaultVariables": null,
"documentGenerator": {
"aspNetCoreToOpenApi": {
"project": "Web.csproj",
"msBuildProjectExtensionsPath": null,
"configuration": null,
"runtime": null,
"targetFramework": null,
"noBuild": true,
"verbose": false,
"workingDirectory": null,
"requireParametersWithoutDefault": true,
"apiGroupNames": null,
"defaultPropertyNameHandling": "CamelCase",
"defaultReferenceTypeNullHandling": "Null",
"defaultDictionaryValueReferenceTypeNullHandling": "NotNull",
"defaultResponseReferenceTypeNullHandling": "NotNull",
"defaultEnumHandling": "Integer",
"flattenInheritanceHierarchy": true,
"generateKnownTypes": true,
"generateEnumMappingDescription": true,
"generateXmlObjects": false,
"generateAbstractProperties": false,
"generateAbstractSchemas": true,
"ignoreObsoleteProperties": true,
"allowReferencesWithProperties": false,
"excludedTypeNames": [],
"serviceHost": null,
"serviceBasePath": null,
"serviceSchemes": [],
"infoTitle": "API",
"infoDescription": null,
"infoVersion": "1.0.0",
"documentTemplate": null,
"documentProcessorTypes": [],
"operationProcessorTypes": [],
"typeNameGeneratorType": null,
"schemaNameGeneratorType": null,
"contractResolverType": null,
"serializerSettingsType": null,
"useDocumentProvider": true,
"documentName": "v1",
"aspNetCoreEnvironment": null,
"createWebHostBuilderMethod": null,
"startupType": null,
"allowNullableBodyParameters": false,
"output": "wwwroot/api/specification.json",
"outputType": "OpenApi3",
"assemblyPaths": [],
"assemblyConfig": null,
"referencePaths": [],
"useNuGetCache": false
}
},
"codeGenerators": {
"openApiToTypeScriptClient": {
"className": "{controller}Client",
"moduleName": "",
"namespace": "",
"typeScriptVersion": 4.3,
"template": "Angular",
"promiseType": "Promise",
"httpClass": "HttpClient",
"withCredentials": false,
"useSingletonProvider": true,
"injectionTokenType": "InjectionToken",
"rxJsVersion": 6.0,
"dateTimeType": "Date",
"nullValue": "Undefined",
"generateClientClasses": false,
"generateClientInterfaces": false,
"generateOptionalParameters": false,
"exportTypes": true,
"wrapDtoExceptions": false,
"exceptionClass": "SwaggerException",
"clientBaseClass": null,
"wrapResponses": false,
"wrapResponseMethods": [],
"generateResponseClasses": true,
"responseClass": "SwaggerResponse",
"protectedMethods": [],
"configurationClass": null,
"useTransformOptionsMethod": false,
"useTransformResultMethod": false,
"flattenInheritanceHierarchy": false,
"generateDtoTypes": true,
"operationGenerationMode": "MultipleClientsFromOperationId",
"markOptionalProperties": false,
"generateCloneMethod": false,
"typeStyle": "Class",
"enumStyle": "Enum",
"useLeafType": true,
"classTypes": [],
"extendedClasses": [],
"extensionCode": null,
"generateDefaultValues": true,
"generateAbstractProperties": false,
"generateAbstractSchemas": false,
"ignoreObsoleteProperties": true,
"excludedTypeNames": [],
"excludedParameterNames": [],
"includeHttpContext": false,
"handleReferences": false,
"generateTypeCheckFunctions": false,
"generateConstructorInterface": false,
"convertConstructorInterfaceData": false,
"importRequiredTypes": true,
"useGetBaseUrlMethod": false,
"baseUrlTokenName": "API_BASE_URL",
"queryNullValue": "",
"inlineNamedDictionaries": false,
"inlineNamedAny": false,
"templateDirectory": null,
"typeNameGeneratorType": null,
"propertyNameGeneratorType": null,
"enumNameGeneratorType": null,
"serviceHost": null,
"serviceSchemes": null,
"output": "ClientApp/src/app/dto/api-dtos.ts"
}
}
}
addtionally its generating 3 fromJS, init and toJSON functions which i also dont want
export class StatusCountDto {
count!: number;
status!: string;
#region I dont want to generate this
init(_data?: any) {
if (_data) {
this.count = _data["count"];
this.status = _data["status"];
}
}
static fromJS(data: any): IssueCountDto {
data = typeof data === 'object' ? data : {};
let result = new IssueCountDto();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["count"] = this.count;
data["status"] = this.status;
return data;
}
#endregion I dont want to generate this
}
any suggesstion?

Special Javascript function in Asp.net?

///<reference name="MicrosoftAjax.js"/>
Type.registerNamespace("AmpUI.Form");
AmpUI.Form.FBuilder = function (element) {
AmpUI.Form.FBuilder.initializeBase(this, [element]);
this._questions = null;
this._formID = null;
this._submitted = null;
this._facID = null;
this._formType = null;
this._autoSaveID = null;
this._typeName = null;
this._enableAutoSave = true;
this._autoSaveInterval = 30000;
this._template = null;
this._btnsave = null;
this._btnsubmit = null;
this._btnsavebottom = null;
this._btnsubmitbottom = null;
this._saveDelegate = null;
this._submitDelegate = null;
this._isautosave = null;
this._saveCallback = null;
this._submitCallback = null;
};
//define proto
AmpUI.Form.FBuilder.prototype = {
initialize: function () {
AmpUI.Form.FBuilder.callBaseMethod(this, "initialize");
//wire up save/submit events
if (this._submitted) {
this.GetResponses(this);
}
else {
//register the dependencies
Array.forEach(this.get_qrefs(), function (e, i, a) {
e.registerDepedency(a);
});
//start autosave
if (this._enableAutoSave && !this._submitted) {
this._autoSaveID = setInterval("$find('" + this._element.id + "').SaveForm(true);", this._autoSaveInterval);
}
if (this._saveDelegate === null) {
this._saveDelegate = Function.createDelegate(this, this.Save);
}
Sys.UI.DomEvent.addHandler($get(this._btnsave), 'click', this._saveDelegate);
Sys.UI.DomEvent.addHandler($get(this._btnsavebottom), 'click', this._saveDelegate);
if (this._submitDelegate === null) {
this._submitDelegate = Function.createDelegate(this, this.SubmitForm);
}
Sys.UI.DomEvent.addHandler($get(this._btnsubmit), 'click', this._submitDelegate);
Sys.UI.DomEvent.addHandler($get(this._btnsubmitbottom), 'click', this._submitDelegate);
}
this._template = "<div class='form_question'><span>{2}</span><div class='form_answer'>{3}</div></div>";
},
dispose: function () {
//init
AmpUI.Form.FBuilder.callBaseMethod(this, "dispose");
},
SaveForm: function (is_auto) {
this._isautosave = is_auto;
var questions = this.get_json();
var sa = new ampWeb.FormService();
sa.SaveFormQuestions(Sys.Serialization.JavaScriptSerializer.serialize(this.get_json()), false, this._typeName, this.onSuccess, this.onFail, this);
},
Save: function () {
this.SaveForm(false);
},
SubmitForm: function () {
var useValidation = true;
var valid = false;
try {
valid = Page_ClientValidate();
}
catch (e) {
useValidation = false;
}
if (valid || !useValidation) {
//stop autosave
clearInterval(this._autoSaveID);
autosaveEnabled = false;
var sa = new ampWeb.FormService();
sa.SaveFormQuestions(Sys.Serialization.JavaScriptSerializer.serialize(this.get_json()), true, this._typeName, this.onSubmitComplete, this.onFail, this);
} else {
$('#' + me._element.id + ' .fbuilder-result').html('Invalid responses were found. Please make all required corrections before submitting.');
}
},
onSuccess: function (s, me) {
$('#' + me._element.id + ' .fbuilder-result').fadeOut();
if (me._isautosave) {
var now = new Date();
$('#' + me._element.id + ' .fbuilder-result').html('Last autosave:' + now.format('hh:mm tt'));
} else {
$('#' + me._element.id + ' .fbuilder-result').html('Form has been saved.');
me._save();
if (me._saveCallback)
me._saveCallback.call(me);
}
$('#' + me._element.id + ' .fbuilder-result').fadeIn();
},
onFail: function (r, me) {
$('#' + me._element.id + ' .fbuilder-result').html(r.get_message());
//var s = new ampWeb.FormService();
//s.ReportAjaxError(r.get_message());
},
onSubmitComplete: function (r, me) {
$('#' + me._element.id + ' .fbuilder-result').html('Your responses have been submitted.');
$('#' + me._element.id).fadeOut('fast', function () {
$('#' + me._element.id).html('<h1>Thank you for submitting.</h1>');
clearInterval(me._autoSaveID);
me._submitted = true;
me.GetResponses(me);
if (me._submitCallback)
me._submitCallback.call(me);
});
},
GetResponses: function (me) {
var sa = new ampWeb.FormService();
sa.GetFormResponses(me._formID, me.WriteToForm, me.onFail, me);
},
WriteToForm: function (answers, me) {
var ar = Sys.Serialization.JavaScriptSerializer.deserialize(answers);
//recreate if missing
if ($('#' + me._element.id + ' #submitted').length == 0) { $('#' + me._element.id).append("<div id='submitted'/>"); }
Array.forEach(ar, function (a) {
$('#' + me._element.id + ' #submitted').append(String.format(me._template, null, null, a.question, a.response));
});
$('#' + me._element.id).fadeIn('fast');
me._submit();
},
resetInterval: function () {
if (this._enableAutoSave) {
clearInterval(this._autoSaveID);
this._autoSaveID = this._autoSaveID = setInterval("$find('" + this._element.id + "').SaveForm(true);", 30000);
}
},
get_questions: function () {
return Sys.Serialization.JavaScriptSerializer.serialize(this._questions);
},
set_questions: function (q) {
this._questions = Sys.Serialization.JavaScriptSerializer.deserialize(q);
},
get_qrefs: function () {
var a = new Array();
Array.forEach(this._questions, function (i) {
a.push($find(i));
});
return a;
},
get_json: function () {
var a = new Array();
Array.forEach(this._questions, function (i) {
a.push($find(i));
});
var b = new Array();
Array.forEach(a, function (i) {
b.push(i.get_json());
});
return b;
},
get_formID: function () {
return this._formID;
},
set_formID: function (value) {
this._formID = value;
},
get_submitted: function () {
return this._submitted;
},
set_submitted: function (value) {
this._submitted = value;
},
set_facID: function (value) {
this._facID = value;
},
get_facID: function () {
return this._facID;
},
set_formType: function (value) {
this._formType = value;
},
get_formType: function () {
return this._formType;
},
set_typeName: function (value) {
this._typeName = value;
},
get_typeName: function () {
return this._typeName;
},
set_enableAutoSave: function (value) {
this._enableAutoSave = value;
},
get_enableAutoSave: function () {
return this._enableAutoSave;
},
set_autoSaveInterval: function (value) {
if (!isNaN(value))
this._autoSaveInterval = value;
},
get_autoSaveInterval: function () {
return this._autoSaveInterval;
},
set_template: function (value) {
this._template = value;
},
get_template: function () {
return this._template;
},
set_btnsave: function (v) {
this._btnsave = v;
},
get_btnsave: function () {
return this._btnsave;
},
get_btnsubmit: function () {
return this._btnsubmit;
},
set_btnsubmit: function (v) {
this._btnsubmit = v;
},
set_btnsave: function (v) {
this._btnsave = v;
},
get_btnsavebottom: function () {
return this._btnsavebottom;
},
get_btnsubmitbottom: function () {
return this._btnsubmitbottom;
},
set_btnsubmitbottom: function (v) {
this._btnsubmitbottom = v;
},
set_btnsavebottom: function (v) {
this._btnsavebottom = v;
},
get_saveCallback: function () {
return this._saveCallback;
},
set_saveCallback: function (f) {
var fn = window[f];
if (fn && typeof (fn) === 'function')
this._saveCallback = fn;
},
get_submitCallback: function (f) {
return this._submitCallback;
},
set_submitCallback: function (f) {
var fn = window[f];
if (fn && typeof (fn) === 'function')
this._submitCallback = fn;
},
add_save: function (handler) {
this.get_events().addHandler("save", handler);
},
remove_save: function (handler) {
this.get_events().removeHandler("save", handler);
},
_save: function () {
var handler = this.get_events().getHandler("save");
if (handler) handler(this, Sys.EventArgs.Empty);
},
add_submit: function (handler) {
this.get_events().addHandler("submit", handler);
},
remove_submit: function (handler) {
this.get_events().removeHandler("submit", handler);
},
_submit: function () {
var handler = this.get_events().getHandler("submit");
if (handler) handler(this, Sys.EventArgs.Empty);
}
}
//register in the namespace
AmpUI.Form.FBuilder.registerClass("AmpUI.Form.FBuilder", Sys.UI.Control);
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
Is it special? for example, i never understand the addHandlder and removeHandler in the Javascript function and also WHAT IS registerNamespace AND WHAT IS Sys.Application.notifyScriptLoaded();?
Is it special? for example, i never understand the addHandlder and removeHandler in the Javascript function and also WHAT IS registerNamespace AND WHAT IS Sys.Application.notifyScriptLoaded();?

Bind Generic List to ASP.NET DropDownList

I am trying to bind generic list to DropDownList an i am not sure how to continue.
here is my code:
protected void Page_Load(object sender, EventArgs e)
{
List<Paths> paths = new List<Paths>();
paths = GetOriginalPaths();
DropDownList1.DataSource = paths;
DropDownList1.DataTextField = "orignalPathName";
DropDownList1.DataValueField = "orignalPathId";
DropDownList1.DataBind();
}
public class Paths
{
public string orignalPathName;
public int orignalPathId;
public string newPathName;
}
public static List<Paths> GetOriginalPaths()
{
return PrepareOriginalPathsData();
}
public static List<Paths> PrepareOriginalPathsData()
{
List<Paths> objPaths = new List<Paths> {
new Paths{orignalPathName = "comp1", orignalPathId= 1} ,
new Paths{orignalPathName = "comp1", orignalPathId= 1} ,
new Paths{orignalPathName = "comp1", orignalPathId= 1} ,
new Paths{orignalPathName = "comp2", orignalPathId= 2} ,
new Paths{orignalPathName = "comp3", orignalPathId= 3} ,
new Paths{orignalPathName = "comp4", orignalPathId= 4}
};
return objPaths;
}
public static List<Paths> GetNewPaths(int orignalPathId)
{
List<Paths> lstNewPaths = new List<Paths>();
Paths objnewPaths = null;
var newPath = (from np in PrepareNewPathsData() where np.orignalPathId == orignalPathId select new { newpathname = np.newPathName, orgId = np.orignalPathId });
foreach (var np in newPath)
{
objnewPaths = new Paths();
objnewPaths.orignalPathId = np.orgId;
objnewPaths.newPathName = np.newpathname;
lstNewPaths.Add(objnewPaths);
}
return lstNewPaths;
}
public static List<Paths> PrepareNewPathsData()
{
List<Paths> objNewPaths = new List<Paths> {
new Paths{newPathName = "part1", orignalPathId= 1} ,
new Paths{newPathName = "part1", orignalPathId= 1} ,
new Paths{newPathName = "part1", orignalPathId= 1} ,
new Paths{newPathName = "part3", orignalPathId= 2} ,
new Paths{newPathName = "part4", orignalPathId= 3} ,
new Paths{newPathName = "part5", orignalPathId= 4} ,
};
return objNewPaths;
}
Fix it!
I had to add this:
public class Paths
{
public string orignalPathName { get; set; }
public int orignalPathId { get; set; }
public string newPathName { get; set; }
}
Your problem might be from the bind prospective you might bind only if not post back!!
If(!Page.IsPostBack)
{
List<Paths> paths = new List<Paths>();
paths = GetOriginalPaths();
DropDownList1.DataSource = paths;
DropDownList1.DataTextField = "orignalPathName";
DropDownList1.DataValueField = "orignalPathId";
DropDownList1.DataBind();
}
What problem are you encountering exactly?
By the way, the DataValueField should be unique. Aas it is it could cause an issue either with the bind, or on post-back.

How to test custom Model Binders in ASP.NET MVC?

I've written some custom model binders (implementing IModelBinder) in our ASP.NET MVC application. I'm wondering what is a good approach to unittest them (binders)?
I did it this way:
var formElements = new NameValueCollection() { {"FirstName","Bubba"}, {"MiddleName", ""}, {"LastName", "Gump"} };
var fakeController = GetControllerContext(formElements);
var valueProvider = new Mock<IValueProvider>();
var bindingContext = new ModelBindingContext(fakeController, valueProvider.Object, typeof(Guid), null, null, null, null);
private static ControllerContext GetControllerContext(NameValueCollection form) {
Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();
mockRequest.Expect(r => r.Form).Returns(form);
Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(mockRequest.Object);
return new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
}
And then I just passed in the bindingContext variable to the BindModel method of the object that implements the IModelBinder interface.
Here's a simple no-mocks way I wrote for you on my blog assuming you use the ValueProvider and not the HttpContext: http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx
[TestMethod]
public void DateTime_Can_Be_Pulled_Via_Provided_Month_Day_Year_Hour_Minute_Second_Alternate_Names()
{
var dict = new ValueProviderDictionary(null) {
{ "foo.month1", new ValueProviderResult("2","2",null) },
{ "foo.day1", new ValueProviderResult("12", "12", null) },
{ "foo.year1", new ValueProviderResult("1964", "1964", null) },
{ "foo.hour1", new ValueProviderResult("13","13",null) },
{ "foo.minute1", new ValueProviderResult("44", "44", null) },
{ "foo.second1", new ValueProviderResult("01", "01", null) }
};
var bindingContext = new ModelBindingContext() { ModelName = "foo", ValueProvider = dict };
DateAndTimeModelBinder b = new DateAndTimeModelBinder() { Month = "month1", Day = "day1", Year = "year1", Hour = "hour1", Minute = "minute1", Second = "second1" };
DateTime result = (DateTime)b.BindModel(null, bindingContext);
Assert.AreEqual(DateTime.Parse("1964-02-12 13:44:01"), result);
}
dict could be refactored like this
FormCollection form = new FormCollection
{
{ "month1", "2" },
{ "day1", "12" },
{ "year1", "1964" },
{ "hour1", "13" },
{ "minute1", "44" },
{ "second1", "01" }
};
var bindingContext = new ModelBindingContext() { ModelName = "foo", ValueProvider = form.ToValueProvider() };

Resources