asp.net selectbox gives null on postback - asp.net-mvc

I am trying to create a user identifier and used a selectbox so they can choose between identifier methods. I did fine one other question here that addressed the situation, but after following that example it still posted back null.
It does show the selectbox correctly aswell as the containing data, however when i push save (post) the selected attr is not added and remains null.
code:
#Html.DropDownList("Authtype", (IEnumerable<SelectListItem>)ViewBag.Authtype)
#Html.DropDownListFor(model => model.Authtype, ViewBag.AvailableAuthorizationTypes as SelectList, "--- Select Category ---", new { #class = "some_class" })
both work (and yes show me the same result, I posted both in the hope that one might bring me further on the right track).
CreateIdentifierModel cim = new CreateIdentifierModel();
IEnumerable<SelectListItem> items = cim.AvailableAuthorizationTypes = Context.AuthorizationTypes.OrderBy(x => x.Name)
.Select(x => new SelectListItem() { Text = x.Name, Value = x.Identifier.ToString() });
ViewBag.Authtype = items;
return View();
When i click save it will go to the post method, but keeps the attr null, eventhough one of the options is selected.
It is probably a brain fart but I can't seem to work out where exactly the problem is and how to fix it. CAn someone help me out?
Kind regards,

Related

WebGrid is returing an error "Column does not exist"

I have the following web grid inside my Razor view on asp.net MVC 5 and i am using Entity framework 6.0:-
Now the web grid is working well on all the paging except for one paging, and when i checked it i found that the WebGrid will return this error:-
Column "SDUser.Department.Definition.DEPTNAME" does not exist.
So seems some items inside this page does not have those navigation properties SDUser.Department.Definition.DEPTNAME,, so how i can overcome this issue?
EDIT:- Here is my updated code, where i added If/Else but still i am getting the same error:-
Before adding new WebGridColumn in gridcolumns, you check whether DEPTNAME property is there or not.
#if(#Model.Content.FirstOrDefault().SDUser.Department.Definition.HasProperty("DEPTNAME"))
{
gridcolumns.Add(new WebGridColumn()
{
ColumnName = "SDUser.Department.Definition.DEPTNAME",
Header = Html.DisplayNameFor(model => model.Content.FirstOrDefault().SDUser.Department.Definition.DEPTNAME).ToString(),
CanSort = true
});
}
Additionally, if you want to check its value is there or empty then use this
#if(#Model.Content.FirstOrDefault().SDUser.Department.Definition.HasProperty("DEPTNAME") && #Model.Content.FirstOrDefault().SDUser.Department.Definition.GetProperty("productSalePrice").Value != String.Empty)
{
//your code
}
Note: I don't know actually your hierarchy of Model, I consider that specific page has not DEPTNAME property. (you are free to modify according to your requirement)

antd prepopulate tags and multi select

I'm working on antd select and having issues with prepopulating it correctly, I can prepopulate the select box via its initialValue field decorator, however it populates strings, there does not appear to be a way to have a value (something I can work around but not ideal), and more importantly if the option is unselected/removed, it is no longer available in the select, unlike standard options. I can include in both select list options and initial value (as demonstrated in code below) but then it allows duplicate auto entry and it appears twice in the drop down list. Any ideas what I'm doing wrong?
Preperation of Preselected and Full Option List
let defaultSelect = [];
let selectList = [];
for (var a = 0; a < this.props.myData.length; a++) {
//push all options to select list
selectList.push(<Select.Option key={this.props.myData[i].id} >{this.props.myData[i].name}</Select.Option>)
//this is my code to pre-populate options, by performing a find/match
let matchedTech = _.find(this.props.myDataPrepopulate, { id: this.props.myData[i].id });
if (matchedTech) {
//notice I can push just the string name, not the name and the id value.
defaultSelect.push(this.props.myData[i].name);
}
}
Select Code
{getFieldDecorator(row.name, {
initialValue: defaultSelect
})(
<Select
tags
notFoundContent='none found'
filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
{selectList}
</Select>
)}
I think I understand your question, even if you posted code that doesn't run.
<Select.Option> works just like the plain html <select><option/></select>. In order to give the option a value it needs a value attribute, which is used to identify the option.
See http://codepen.io/JesperWe/pen/YVqBor for a working example.
The crucial part transformed to your example would become:
this.props.myData.forEach( data => {
selectList.push(<Select.Option value={data.id} key={data.id}>{data.name}</Select.Option>);
} );
defaultSelect = this.props.myDataPrepopulate.map( data => data.id );
(I took the liberty to use a bit more modern code patterns than your original)

Using Html.DropDownListFor and selecting a value inside the SelectList will not work together

I am working on an asp.net mvc-5 web application and i wrote the following inside my Get Edit action method to buld a dropdownlist:-
var t=await unitofwork.SkillRepository.getallSkillCategories().ToListAsync();
ViewBag.SkillCategoryID = new SelectList(t, "SkillCategoryID", "Name",skill.SkillCategoryID);
and inside the view i wrote the following:-
#Html.DropDownListFor(model => model.SkillCategoryID,(SelectList) ViewBag.SkillCategoryID,"--please select--", null)
but the above did not work together , as the current SkillCategoryID will not be selected , and i will always get "--please select--". to get this fixed i have to do one of the following:-
1)to modify my action method as follow (remove the skill.SkillCategoryID):-
ViewBag.SkillCategoryID = new SelectList(t, "SkillCategoryID", "Name");
2)or to modify my view to pass null instead of mentioning the ViewBag:-
#Html.DropDownListFor(model => model.SkillCategoryID,null,"--please select--", null)
so why my first approach did not work ??

Cascading Dropdowns Using Knockout.js

I'm able to get this working except for two things that I just can't figure out:
Problem 1: I need to get both of the following but right now can only achieve one OR the other:
Select options need to have value and text
The selectedOption captured in the model needs to return the object of the selected option and not just the value of the option
I can affect which one of these works by including or excluding the following from my select markup:
...data-bind="optionsValue = 'Id'"...
How can I achieve both?
Problem 2: I need to set the selected option in the dropdown to an object I retrieve from a cookie containing the user's preferred value. My below implementation does not succeed in setting the selected value at all. What am I missing?
$(document).ready(function(){
var userOption = $.cookie("userPref") == null ? undefined : JSON.parse($.cookie("userPref"));
var model = function(){
this.options = ko.observableArray();
this.childOptions = ko.observableArray();
this.selectedOption = ko.observable(userOption); //this does nothing to set the value
this.selectedOption(userOption); //this also does nothing
this.options.subscribe(function(){
//this.selectedOption() returns an object if optionsValue is excluded from select databinding and returns option value if included
$.cookie("userPref", JSON.stringify(this.selectedOption());
this.childOptions(undefined);
this.childOptions(this.selectedOption() ? this.selectedOption().children : []);
}.bind(this));
};
var viewModel = new model();
ko.applyBindings(viewModel);
$.ajax({
type: "GET",
url: "myurl",
success: function(data){
viewModel.options(data);
}
});
});
<select data-bind="options: options, optionsText: 'text', optionsValue: 'Id', value: selectedOption, optionsCaption: 'Select Option'"></select>
You can't use the entire object as the value because an option value must be a simple type: string, int, etc. I suppose you could JSON encode the object (so it's a string) and set the value to that, but then you'd have to reciprocate on the backend and decode the posted string value back into an object and somehow work with that. However, said object would be disconnected from EF, so you'd have to fetch the object new from the database anyways in order to do anything meaningful with it. And, your second problem is the same as your first, you can't use a full object.
The way this is usually done is with ids. You make the option value the object's id. Then, you can set the selected option based on the object's id from the cookie. When you get to the backend, if you need to work with the object, you fetch it by the posted id. Anything else is not really a tenable situation.

Saving files and names to database table using for each on request.files

MVC3 VB.NET Application. I have multiple file upload boxes on a form in my mvc3 application. Request.Files shows 3 files when I put a break point in the below function and look at it.. Problem is other than coding a counter and using a select case I dont see a way to handle saving each file name to the database column it belongs to... Is there away to assign the variable on the fly I guess you could say So that the foreach loop would drop the file in the correct column.. Ie handoutFile1, handoutFile2 , handoutFile3, Etc.... As it stands the below will overwrite the filename in handoutfile1 every time the loop is gone through....I thought about throwing a counter in the loop and just put a select case on it to assign the db column based on the counter number. Seems like a cheap work around though.
For Each File As String In Request.Files
Dim hpf As HttpPostedFileBase = TryCast(Request.Files(File), HttpPostedFileBase)
If hpf.ContentLength = 0 Then
Continue For
End If
Dim savedfileName As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + hpf.FileName
hpf.SaveAs(savedfileName)
_filename = hpf.FileName
courses.handoutFile1 = _filename
Next
I dont know VB.Net but i will try to answer in C# code,
In your action you can define in parameter as
[HttpPost]
public ActionResult Index(IList<HttpPostedFileBase> postedFiles)
{
foreach (var file in postedFiles)
{
//
}
return View();
}
and in the view like the following,
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>TestModel</legend>
#Html.TextBox("postedFiles[0]",null, new { type = "file" })
#Html.TextBox("postedFiles[1]",null, new { type = "file" })
#Html.TextBox("postedFiles[2]",null, new { type = "file" })
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Your database design seems wrong. Instead of trying to save each individual file in a separate column, you could create another table that will contain all files as rows and which will have a foreign key to the first table to match the record. So you will basically have courses.handoutFiles which will be an array instead of having courses.handoutFile1, courses.handoutFile2, ...
If on the other hand for some reason you need to work with the initial schema and save into separate columns, you don't have much choice other than using ugly code.

Resources