Im pretty new to MVC. Im trying to populate a drop downlist with currencies retrieved from database. What am I doing wrong?
#model IEnumerable<DSABankSolution.Models.ExchangeRates>
#{
ViewBag.Title = "Exchange Rates";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br /> <br />
<input type="text" size="5" value="1" />
#Html.DropDownList("currency", Model.Select(p => new SelectListItem{ Text = p.Name, Value = p.ID}))
to
#Html.DropDownList("currency", Model.Select(p => new SelectListItem { Text = p.Name, Value = p.ID }));
<br /> <br /> <input type="submit" name="Convert" />
ExchangeRate Model:
public class ExchangeRates
{
public string ID { get; set; }
public string Name { get; set; }
}
ExchangeRate Controller:
public ActionResult Index()
{
IEnumerable<CommonLayer.Currency> currency = CurrencyRepository.Instance.getAllCurrencies().ToList();
//ViewBag.CurrencyID = new SelectList(currency, "ID");
//ViewBag.Currency = new SelectList(currency, "Name");
return View(currency);
}
Currency Repository:
public List<CommonLayer.Currency> getAllCurrencies()
{
var query = from curr
in this.Entity.Currencies
select curr;
return query.ToList();
}
Error I am getting:
The model item passed into the dictionary is of type
'System.Collections.Generic.List1[CommonLayer.Currency]', but this
dictionary requires a model item of type
'System.Collections.Generic.IEnumerable1[DSABankSolution.Models.ExchangeRates]'.
Thanks!
The error says it all. You are returning a collection of Currency as shown by this code
IEnumerable<CommonLayer.Currency> currency
and yet your view expect as a collection of ExchangeRates
#model IEnumerable<DSABankSolution.Models.ExchangeRates>
so you either change the declaration in your view to
#model IEnumerable<CommonLayer.Currency>
or return a list of ExchangeRates from your controller method
Your view expects a strongly typed model of type
IEnumerable<DSABankSolution.Models.ExchangeRates>
However,you are passing
IEnumerable<CommonLayer.Currency>
back to view.
Related
I am student. I am new to ASP.NET MVC and I google it and I tried see I write all code but viewbag not properly working
I am transferring data and using the viewing but not transferring the dropdown value
type.cs
public class Type
{
//public int Value { get; set; }
//public string Text { get; set; }
public int typeid { get; set; }
public string typename { get; set; }
}
public class TypeViewModel
{
//public List<Type> TypeDetaills { get; set; }
public SelectList TypeList { get; set; }
}
HomeControlle.cs
TypeViewModel TypeViewModel = new TypeViewModel();
public ActionResult Index()
{
SqlCommand cmd = new SqlCommand("getType", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cn.Open();
da.Fill(ds);
DataTable dt = ds.Tables[0];
List<Type> objcountry = new List<Type>();
SelectList objlistofcountrytobind = new SelectList(dt.AsDataView(), "typeid", "typename", 0);
TypeViewModel.TypeList = objlistofcountrytobind;
ViewBag.typename = TypeViewModel.TypeList;
cn.Close();
return View();
}
[HttpPost]
public ActionResult CreateCustomer(Customer customer,string TypeList)
{
customer.Type = TypeList;
customer.CustomerName = cust;
return RedirectToAction("Index");
}
Index.cshtml
#model projectname.Models.TypeViewModel
#{
ViewBag.Title = "Index";
//var t = ViewBag.typename;
}
<h2>Type Query</h2>
#using (Html.BeginForm("CreateCustomer", "Home", FormMethod.Post, new { TypeList = #ViewBag.typename }))
{
<div class="form-group">
<div class="row">
<label>Type Name:</label>
#Html.DropDownListFor(model => model.TypeList, ViewBag.typename as SelectList)
#*#Html.Hidden("TypeList", #ViewBag.typename);*#
#*#Html.HiddenFor("TypeList", #ViewBag.typename);*#
#*#Html.HiddenFor(x => x.TypeList)*#
#*<input type="hidden" value="#ViewBag.typename" />*#
#*#Html.DropDownList("typeid", t as SelectList)*#
#*#Html.DropDownListFor(x => x.typename, new SelectList((IEnumerable<Type>)t, "typeid", "typename"))*#
</div>
</div>
<div class="form-group">
<div class="row">
<label>Customer Name:</label>
<input type="text" id="cust" name="cust" />
</div>
</div>
<input type="submit" />
}
see i select the runtime warranty from the drop down
I am trying to pass controller warranty not 2
see stored procedure getType fill this stored procedure in dropdown
I tried hiddenfor attribute but it not work
I want the pass warranty to createcustomer controller not 2
please help
Before trying to create code, you have to learn that the first letter in MVC is for model. So you have forget that viewbag is even exist. Create a view model , assign data and pass it from the action and use it inside of the view
TypeViewModel.TypeList = objlistofcountrytobind;
return View (TypeViewModel)
and you can only assign as a hidden (or not hidden) the primitive types (as string or int) not the whole instanse of the class
Pass text and value field same, if you want the text field to be posted back to the controller action method. By default dropdownlist uses value field.
Change that line!
SelectList objlistofcountrytobind = new SelectList(dt.AsDataView(), "typename", "typename", 0);
You can modify your view model as described in the following post: How to get DropDownList SelectedValue in Controller in MVC.
Or you can use the JavaScript:
#Html.DropDownListFor(model => model.TypeList,
ViewBag.type_name as SelectList,
new { onchange=" { var ddltext = $(`#TypeList option:selected`).text();$('#textvalue').val(ddltext);}" })
#Html.Hidden("typeList", "")
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
I need to do a calculator in ASP.NET MVC.
For the beginning I want to receive the value from the input field in controller and prefix it with the string "123". At the end I will process the expresion received and return the result.
I have the following model:
namespace CalculatorCloud.Models {
public class Calculator
{
public string nr { get; set; }
} }
In the view I am using the model:
#model CalculatorCloud.Models.Calculator
#{
ViewBag.Title = "Calculator";
}
#using (Html.BeginForm("Index", "Home"))
{
<div>
<div class="header">
#Html.TextBoxFor(m => m.nr, new { #id = "nr"})
<input type="button" id="C" name="C" value="C" />
<input type="button" id="back" name="back" value="<-" />
[...]
<div class="sum">
<input type="submit" value="=" />
</div>
</div>
}
The controller is like this:
namespace CalculatorCloud.Controllers
{
public class HomeController : Controller
{
Calculator model = new Calculator();
public ActionResult Index(string nr)
{
model.nr = "123" + nr;
return View(model);
}
}
}
I have the following problem: when pressing on submit button I am expecting to be displayed on the textbox the value from that was previously in the textbox, prefixed with the string "123".
But now it is kept the value from the textbox without the string "123".
Can someone help me with this?
Thank you! :)
If you want to modify the value of a model property in a postback action you will need to remove it from the ModelState:
public ActionResult Index(string nr)
{
ModelState.Remove("nr");
model.nr = "123" + nr;
return View(model);
}
The reason for this is that Html helpers such as TextBoxFor will first look at the value present in the ModelState and then in your view model property when rendering the value. This is by design.
How can I prepare a model for Dropdownlist static values (not retrieved from database) like enum or list in MVC Model so that it could be used many times in a project? I would appreciate if you can give a good article? Thanks.
As always you could start with a view model:
public class MyViewModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "Item 1" },
new SelectListItem { Value = "2", Text = "Item 2" },
new SelectListItem { Value = "3", Text = "Item 3" },
};
}
}
}
then a controller:
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
and finally a view:
#model MyViewModel
#Html.DropDownListFor(x => x.SelectedValue, Model.Values)
For enums you could use some of the many posts out there illustrating custom helpers. Here's one blog post illustrating such helper: http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx
Finally I have found the solution by describing the parameters as hidden input. I am not sure if there is a more elegant method in order to pass the parameters from View to Controller. Thank you so much for your good sample. I also marked as helpful all of your replies. Here is my final code for those who might encounter a similar problem:
ApplicantViewModel:
public class ApplicantViewModel
{
public IEnumerable<Applicant> Applicants { get; set; }
//Codes for Dropdownlist values
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values
{
get
{
return new[]
{
new SelectListItem { Value = "pdf", Text = "Pdf" },
new SelectListItem { Value = "excel", Text = "Excel" },
new SelectListItem { Value = "word", Text = "Word" }
};
}
}
}
ApplicantController:
public ViewResult Reporting()
{
var model = new ApplicantViewModel();
return View(model);
}
public ActionResult RenderReport(string SelectedValue, string name, string fileName, string dataSource, string table, string filter)
{
//Codes for rendering report
...
}
Reporting.cshtml:
#model MyProject.Models.ApplicantViewModel
#using (Html.BeginForm("RenderReport", "Applicant", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div>
#Html.DropDownListFor(model => model.SelectedValue, Model.Values, "-- select an option --")
<input type="hidden" name="name" value="Report1"/>
<input type="hidden" name="fileName" value="image rapor"/>
<input type="hidden" name="dataSource" value="ApplicantDataset"/>
<input type="hidden" name="table" value="ApplicantsView"/>
<input type="hidden" name="filter" value="David"/>
<input type="submit" value="submit" />
</div>
}
Having trouble creating a list of radio buttons that are grouped together, in MVC 3 specifically, but this also applies to MVC 2.
The problem arises when radio buttons are generated using Html helpers and the model is part of an array.
Here is the cut down version of my code.
public class CollectionOfStuff {
public MVCModel[] Things { get; set }
}
/*This model is larger and represents a Person*/
public class MVCModel {
[UIHint("Hidden")]
public string Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
/*Assigned to new CollectionOfStuff property Things*/
var items = new[] {
new MVCModel() { Id="0" Name = "Name here" }, new MVCModel() { Id="1" Name = "Name there" }
}
My parent view
#model CollectionOfStuff
#for (int i = 0; i < Model.Things.Length; i++) {
#Html.EditorFor(m => m.Things[i]);
}
My view rendering individual MVCModel objects
#Model MVCModel
#{
var attr = new {
Checked = Model.IsSelected ? "checked=checked" : ""
};
}
#Html.RadioButtonFor(model => model, Model.Id, attr)
Produces this output:
<input type="radio" value="0" name="MVCModel[0]" id="MVCModel_0_" data-val-required="You need to choose" data-val="true" />
<input type="radio" value="1" name="MVCModel[1]" id="MVCModel_1_" data-val-required="You need to choose" data-val="true" />
The radio buttons are not grouped, however it has the obvious advantage of writing out the meta data for validation.
The other way is by calling:
#Html.RadioButton(name: "GroupName", value: Model.Id, isChecked: Model.IsSelected)
Produces:
<input type="radio" value="0" name="MVCModel[0].GroupName" id="MVCModel_0__GroupName">
<input type="radio" value="1" name="MVCModel[1].GroupName" id="MVCModel_1__GroupName">
Again, this doesn't produce the desired result. It's also missing the validation meta data.
Another other option is creating a custom template, but the problem with this approach is that all the meta data required for validation is not present.
Any ideas on how I can create grouped radio buttons or obtain meta data so I can create a template myself?
You haven't shown how does your view model look like but you could group them by some property. So let's take an example:
public class MyViewModel
{
[Required]
public string SomeProperty { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
#model AppName.Models.MyViewModel
#using (Html.BeginForm())
{
<div>A: #Html.RadioButtonFor(x => x.SomeProperty, "a")</div>
<div>B: #Html.RadioButtonFor(x => x.SomeProperty, "b")</div>
#Html.ValidationMessageFor(x => x.SomeProperty)
<input type="submit" value="OK" />
}
Now if you want to preselect some radio simply set the property of the view model to the corresponding value of the radio instead of writing some ugly C# code in your views:
public ActionResult Index()
{
var model = new MyViewModel
{
SomeProperty = "a" // select the first radio
};
return View(model);
}
Obviously this technique works with any simple property type (not only strings) and with any number of radio buttons that could be associated to this property.
I have an asp.NET mvc 3 with razor website. I have a web page that is displaying a list of data from a database in a form such as:
<input type="text" name="blah1" value="blah" />
<input type="text" name="blah2" value="blahblah" />
<input type="text" name="blah3" value="blahblah" />
Each row above is assoicated with a primary key. When the user hits submit and posts back the FormCollection to the controller.. how do I go about getting the primary keys of each blah? Do I add a hidden field for each row that contains the primary key of that row? If so, how do I know which blah it is associated with as the FormCollection is just a dictionary?
I would recommend you using a view model:
public class MyViewModel
{
public string Id { get; set; }
public string Text { get; set; }
}
and then in your controller action you would send a list of those models to the view:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel { Id = "1", Text = "blah" },
new MyViewModel { Id = "2", Text = "blahblah" },
new MyViewModel { Id = "3", Text = "blahblah" },
};
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
// Here you will get a collection of id and text for each item
...
}
}
and the view you could use hidden fields for the id and a textbox for the value:
#model IEnumerable<MyViewModel>
#using (Html.BeginForm())
{
#Html.EditorForModel()
<input type="submit" value="OK" />
}
and the corresponding editor template (~/Views/Shared/EditorTemplates/MyViewModel.cshtml):
#model MyViewModel
#Html.HiddenFor(x => x.Id)
#Html.TextBoxFor(x => x.Text)