I am trying to pass an value from my view to my controller:
public ActionResult Create(int id)
{
ViewBag.ConferenceRegesterId = id;
return View();
}
As you can see in create action i save my id in viewbag .i need this id in post back so i have this code for postback :
[HttpPost]
public ActionResult Creat(MvcConference.Models.Details1 ObjDetails)
{
dbcontext.Details1.Add(ObjDetails);
dbcontext.SaveChanges();
List<MvcConference.Models.Details1> lstuser = dbcontext.Details1.ToList();
return View("Index");
}
I use this code to assign my viewbag value to my model item in my create view
#Html.HiddenFor(model => model.ConferenceRegesterId=ViewBag.ConferenceRegesterId)
but finally after executing i got this error :
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1963: An expression tree may not contain a dynamic operation
I will be apprciate for any help
Best regards
You can't just assign the value for a model's property in a view (through viewbag) like the way you're currently doing, because you're not creating an instance of the class. Please note that only value bound to the input elements are posted back to the controller.
Slightly change the way your program currently behaves. Your create action in the controller will crate an instance for your viewmodel and initialize the required members (ConferenceRegesterId). This model will be strongly bound to the create view.
public ActionResult Create(int id)
{
MvcConference.Models.Details1 viewmodel = new MvcConference.Models.Details1();
viewmodel.ConferenceRegesterId = id;
return View(viewmodel);
}
Your create view
#model MvcConference.Models.Details1
#using (Html.BeginForm())
{
......
#Html.HiddenFor(model => model.ConferenceRegesterId)
}
Now your ObjDetails in POST action can access the value of ConferenceRegesterId you passed through the hiddenfield input element.
You don't need any model. That's simple problem. When you use a ViewBag you must convert that object to static object on your Razor View.
Like that;
#{
string varName = ViewBag.varName;
}
And you will not see again that;
Compiler Error Message: CS1963: An expression tree may not contain a dynamic operation
Related
This error throws me when I am pass data to the model and call the view.
Here is the full error shows,
An unhandled exception occurred while processing the request.
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Castle.Proxies.VendorProxy', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IList`1[Nop.Web.Models.Common.VendorDetailModel]'.
Now, I create one model, one view and controller in nopcommerce 4.2.
Here is my model place,
Nop.Web => Models => Common => VendorDetailModel
Here is the code of mode
public VendorDetailModel()
{
Address = new List<AddressModel>();
}
public string Name { get; set; }
public IList<AddressModel> Address { get; set; }
Here is the controller placed
Nop.Web => Controllers => CommonController => Vendordetail(method)
Here is the controller code
public virtual IActionResult Vendordetail(int vendorId)
{
var model = _vendorService.GetVendorById(vendorId);
return View("Vendordetail",model);
}
Here is the view placed,
Nop.Web => Views => Common => Vendordetail.cshtml
Here is the view code
#model VendorDetailModel
content.......
So, this error is showing when I place the #model VendorDetailModel in view file while if I remove this line then error is not showing. But I remove this line then how can I get the value without model.
Maybe at some point in your view, you are passing the wrong model to a partial view. In my case, my view was getting a model for "BOX", and using a partial view expecting a model for "ORDER" but I didn't explicitly pass the "ORDER" model to the partial, so the partial view was getting the default "BOX" model, which was wrong and was triggering this "Castle.model.proxy" error.
I got the solution.
problem is that I didnt giving the value to the model, just passing the store data variable from controller to view.
Here is my solution code.
var model = new VendorDetailModel();
var vendor = _vendorService.GetVendorById(vendorId);
model.Name = vendor.Name;
return View(model);
and view page is same as it is previous
I have the following code in controller and razor view.
When Upload() is called I want to return another view with the model as the parameter so it's accessible within the view.
But I keep getting "Object reference not set to an instance of an object" on #Model.PhoneNumber
Another question is that does the model has to be strongly typed? It seems when I pass in new { PhoneNumber = "123456" } the property can't be accessed from view either.
[HttpGet]
[Route("{code}/CertificateValidation")]
public ActionResult CertificateValidation()
{
return View();
}
[HttpPost]
public ActionResult Upload(FormCollection file)
{
return View("CertificateValidation", new IndexViewModel { PhoneNumber = "123456" });
}
View:
model WebApplicationMVC.Models.IndexViewModel
<p>#Model.PhoneNumber </p>
Problem is with your get Method.
Your following method does not return any model. So Model is null so it gives error.
[HttpGet]
[Route("{code}/CertificateValidation")]
public ActionResult CertificateValidation()
{
var model = new IndexViewModel();
return View(model);
}
The way you are returning the view with the model is correct and should not have any issue.
return View("CertificateValidation", new IndexViewModel { PhoneNumber = "123456" });
That said, most probably your actual code would not be like this and might be fetching data from some source like a database probable, which could be returning null which you can investigate by debugging or writing null checks.
For the second answer, if you are specifying the type of the model in the view with the #model directive, you have to provide an instance of this type in the return View() method call. Alternatively you can use the #model dynamic which would allow you to pass anything as the model. See this link
I'm trying to pass the id value of the url into a textboxfor of a view like the picture below,and i have no idea how to do it.
here's the image
update, the problem is that value of id is pass from another view by action link like this
#Html.ActionLink("Chose Car Type for Car", "Addcar", "Car", new { id = item.Ctid }, null)|
so what i want is to pass an attribute from two different views belong to 2 different controller and different action, how can i do that, i just need to make the attribute from one view appear in other under any type like viewbag or anything.
when you enter your URL ,you are trying to call a Controller . so you should catch the parameter as argument of the controller method , and then pass it to view with something like viewbag
in your car controller:
public ActionResult AddCar(int Id)
{
ViewBag.Id= Id;
return View();
}
in your view :
#{int id = ViewBag.Id; }<br />
#Html.TextBox("TextboxName",#id)
One simple example in your context-
public class HomeController : Controller
{
public string Index(string id, string name)
{
return "ID =" + id+"<br /> Name="+name;
}
}
else while returning view, you can do something like-
return View("Act", new { yourQueryString= "itsValueHere" });
And after that you can-
Textboxfor is binding data with Model. So you have to bind view with a model.
make AddCart action with id paramter, after that you can see when you pass the value that will appear in id parameter. After that load the model or make the model with the id and properties and pass to the view.
In the View
#Html.TextBox("TextboxName",ViewBag.YourProperty)
In the Controller
ViewBag.YourProperty= 'test';
You should pass the ID through the model defined for this view.
Another way is to use Html.TextBox() and provide the value manually using #Request.RequestContext.RouteData.Values["id"]
Ive just been trying to expand on a previous project by adding a DropDownList on to home/contact.cshtml.
My issue is i keep receiving the following error when loading the page in firefox
Error:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
There is no ViewData item of type 'IEnumerable' that has the key 'displayGraph'
I have another dropdownlist on another page that works fine(same method), if I copy the same code into a new project it works fine, could anyone advise me what could cause this?
contact.cshtml - code snippet
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
Filter By: #Html.DropDownList("displayGraph","Select a Graph")
<input type="submit" value="Filter" />
</p>
}
HomeController - Code Snippet
public ActionResult Index()
{
string chart1 = "Num Each Model Processed", chart2 = "Another chart to be assigned";
var GraphLst = new List<string> { chart1, chart1 };
ViewBag.displayGraph = new SelectList(GraphLst);
string userName = User.Identity.Name;
return View();
}
Graphdropdownmodel - code snippet
namespace TestSolution.Models
{
public class GraphDropdownModel
{
public IEnumerable<SelectListItem> Graph{ get; set; }
}
public class GraphDBContext : DbContext
{
public DbSet<GraphDropdownModel> Graphs { get; set; }
}
}
Try using #Html.DropDownListFor
#Html.DropDownListFor(model => model.value, (SelectList)ViewBag.displayGraph)
The problem here is that ViewBag is a dynamic property, and the DropDownList can't figure out that it has to cast the actual type (which is SelectList) to an IEnuerable<SelectListItem> for the conversion operator to work.
However, this is probably a good thing because even if you did get it to work, you would be headed for trouble. As soon as you tried to post back the data to the server, the MVC model binder would get confused because you would now have an item in the ModelState called displayGraph which is of type SelectList and you are also posting string value with the name of displayGraph.
This is why using a DropDownListFor() is better (or at least using the overload of DropDownList() that takes a separate property name and collection list).
Always name your selected property different from the collection you use to populate your dropdown, it will save you a lot of headaches.
This question is related to another I ask recently, it can be found here for some background information.
Here is the code in the Edit ActionResult:
public virtual ActionResult Edit(int id)
{
///Set data for DropDownLists.
ViewData["MethodList"] = tr.ListMethods();
ViewData["GenderList"] = tr.ListGenders();
ViewData["FocusAreaList"] = tr.ListFocusAreas();
ViewData["SiteList"] = tr.ListSites();
ViewData["TypeList"] = tr.ListTalkbackTypes();
ViewData["CategoryList"] = tr.ListCategories();
return View(tr.GetTalkback(id));
}
I add lists to the ViewData to use in the dropdownlists, these are all IEnumerable and are all returning values.
GetTalkback() returns an Entity framework object of type Talkback which is generated from the Talkback table.
The DropDownListFor code is:
<%: Html.DropDownListFor(model=>model.method_id,new SelectList(ViewData["MethodList"] as IEnumerable<SelectListItem>,"Value","Text",Model.method_id)) %>
The record I am viewing has values in all fields. When I click submit on the View, I get an Object reference not set to an instance of an object. error on the above line.
There are a number of standard fields in the form prior to this, so the error is only occurring on dropdown lists, and it is occurring on all of them.
Any ideas? This is my first foray in to MVC, C#, and Entity so I am completely lost!
If you have [HttpPost] method like that
[HttpPost]
public ActionResult Edit(Talkback model)
{
//Do something with model
return View(model);
}
You have to fill ViewData again. If you don't do it, you'll have Object reference not set to an instance of an object errors.
The best thing to do would be to follow POST-REDIRECT-GET patter and do it like that:
[HttpPost]
public ActionResult Edit(Talkback model)
{
//Do something with model
return RedirectToAction("Edit", new { id = model.id });
}
You'll have ViewData filled again by [HttpGet] method.