My URL is something like,
localhost:19876/PatientVisitDetail/Create?PatientId=1
I have to retrieve the PatientId from the URL and pass it along the request.
I tried,
Url.RequestContext.Values["PatientId"] => System.Web.Routing.RequestContext does not contain a definition for 'Values' and
no extension method 'Values' accepting a first argument of type 'System.Web.Routing.RequestContext'
Again I tried,
RouteData.Values["PatientId"] => an object reference is required for the non static field, method
or property 'System.Web.Routing.RouteData.Values.get'
EDIT:
Based on the Jason's comment below, I tried Request["SomeParameter"] and it worked. But, there is also a warning to avoid that.
Any ideas how to avoid this for my scenario ?
My scenario:
There is a Create action method in my controller for creating a new patient.
But, I need to go back to the last page,
If I give something like,
#Html.ActionLink("Back to List", "Index")
=> this wont work because my controller action method has the following signature,
public ActionResult Index(int patientId = 0)
So, I must pass along the patientId in this case.
You are effectively circumventing the whole point of MVC here. Have an action which accepts PatientId i.e.
public ActionResult Create(int patientId)
{
return View(patientId);
}
Then in your view use that value e.g.
#model int
#Html.ActionLink("Back", "LastAction", "LastController", new { patientId = #Model })
This is the MVC way.
From your controller, you could put the PatientId in a ViewBag and access it from your View
public ActionResult Create()
{
ViewBag.PatientId = 1;
return View();
}
View
Html.ActionLink("Back", "Index", new { PatiendId = ViewBag.PatientId })
Related
I need to display a value in an editable textbox on my mvc page when it first loads if it exists. I've got a function that will take care of getting the value that I need, but I need to pass in parameters from the current model to get what I need from the database.
The problem I'm having is getting this value into the textbox. What I tried was
cshtml:
#Html.TextBoxFor(model => model.AdjustedLiabilityAmount, new { #Value=OBS_LIB.BLL.JeopardyAssessment.JeopardyAssessment.GetLatestAdjustedLiabilityAmount(Model.DOTNumber, Model.LiabilityAmount))}
I get a red squiggly that "The name 'Value' does not exist in the current context"
So I tried a different technique I read about which was like this.
Controller:
public ActionResult Index()
{
ViewBag.AdjustedValue = OBS_LIB.BLL.JeopardyAssessment.JeopardyAssessment.GetLatestAdjustedLiabilityAmount(Model.DOTNumber, Model.LiabilityAmount);
cshtml:
#Html.TextBoxFor(model => model.AdjustedLiabilityAmount, new { #Value=ViewBag.AdjustedValue)}
This time I'm getting the red squiggly "The name 'Model' does not exist in the current context."
I'm sure I'm just missing something basic here as I'm new to MVC.
Any help is much appreciated.
Entire ActionResult Index:
public ActionResult Index()
{
ViewBag.AdjustedValue = OBS_LIB.BLL.JeopardyAssessment.JeopardyAssessment.GetLatestAdjustedLiabilityAmount(Model.DOTNumber, Model.LiabilityAmount);
var Report = new OBS_LIB.DTO.JeopardyAssessmentReport();
Report.Stage = 1;
Report.Status = "Active";
Report.ReportItems = OBS_LIB.BLL.JeopardyAssessment.JeopardyAssessment.GetJAReportItems(Report.Stage, Report.Status);
return View(Report);
}
You want to do something like this:
Class:
public class ModelClassHere {
public float Liability {get;set;}
}
Controller:
public ActionResult Index(ModelClassHere model) {
model.Liability = 10.00;
return View(model); // pass model to the view
}
View:
#Html.TextBoxFor(x => x.Liability) // 'x' can be anything
EDIT*
If you already have a model and need to pass one simple value:
Controller:
public ActionResult Index(ModelClassHere model, string otherValue) {
model.Liability = 10.00;
ViewBag.Liability = model.Liability;
return View(model); // pass model to the view
}
View:
<input type="text" id="otherValue" name="otherValue" value="#ViewBag.Liability.ToString()" />
You can use
#Html.TextBox("AdjustedLiabilityAmount", (Decimal)ViewBag.AdjustedValue)}
Or
#Html.TextBox("AdjustedLiabilityAmount", Model.AdjustedLiabilityAmount == null ? (Decimal)ViewBag.AdjustedValue : Model.AdjustedLiabilityAmount)}
In decimal type you put your the type that you need.
You need to pass your model in the
Controller
return view(myModelName);
make sure you have access to it in your controller.
also your view has to reference the model in the #model line at the top.
Finally to call the model it would be
view:
Model.myModelName
Using MVC 5 and Razor pages.
The scenario is when I cast (int)colour to a Item property called Colour which is of type INT in my HttpGet method. This value should be passed to the ViewModel, and i store it as a hiddenfield on razor view.
So when debugging my code:
return View(viewModel); the viewModel.Colour = 23 - which is correct.
This will now display the Razor view, and inside this razor view i store the model.House value into a hidden field, so i can perform a HttpPost.
At this stage my raw URL is:
applicationName/Orange/Item/Create?date=2014-08-05&_1236723545
Notice there is Orange in the Colour param in the url, and also a model which is at the end, which has a Colour property, which has the number 23.
Now once iv completed filling the form in, and press save, the ModelState is not valid at this stage, because for some odd reason in the razor view
#Html.HiddenFor(model => model.Colour)
stores the string value "Orange" instead of 23, which has been provided by the model. Now i understand the names clash in the URL and my object model, but surely this should work.
My Route Config
routes.MapRoute(
name: "Item",
url: "{colour}/{controller}/{action}/{id}",
defaults: new { controller = "Item", action = "Index", id = UrlParameter.Optional }
);
My Get method:
[HttpGet]
public ActionResult Create(Colour colour, DateTime? date)
{
var viewModel = new Item()
{
ItemDate = (!date.HasValue ? DateTime.Now.Date : date.Value),
Colour = (int) colour,
ItemTypeId = 1
};
return View(viewModel);
}
My Post Method
[HttpPost]
public ActionResult Create(Item item)
{
if (ModelState.IsValid)
{
_itemService.Create(item);
return RedirectToAction("Index", "Item", new { date = item.itemDate.ToString("yyyy-MM-dd") });
}
return View(item);
}
SO my question is how do i get my razor view to ignore the colour that is written in url and to use colour which is the Item property. So instead of "Orange" it should be 23.
Can anyone advise?
Explicitly excluding it is a good way to go:
public ActionResult YourMethod([Bind(Exclude = "Colour")] Item item{
//Implementation
}
Another option is to explicitly INCLUDE all of the parameters from the request that you want to bind to:
public ActionResult YourMethod([Bind(Include = "NotColour1, NotColour2")] Item item{
//Implementation
}
I tend to prefer this method because
Visual Studio stubs it out this way when it scaffolds stuff (not a technically sufficient reason, but good enough)
Gives me a bit more confidence security-wise, because you say what IS and not what CANT be and I therefore feel just a little bit more in control.
I agree with the suggestion, though, that you should look into choosing different names for non-related things (or at least put them in separate namespaces?)
So I got this webproject i'm working on, and in 4/5 views Im using
#Html.ActionLink("Back to List", "Index", new { id=Model.ClientID})
All of the views return me to my list exept my "Create New View"
This will also be the only view not to load, giving me the exeption of "System.NullReferenceException"
I'm confused on why this is the only view that won't let me pass a clientID to it ( since i need not only it but also the CountyID to create a new County, And more so telling me that it is null.
If i remove the line of code above my code runs fine ( exept adding my 2 ID fields into the create view obviously ) wich made me think it may be my controller.
Here is my action from givin controller for create
// GET: /County/Create
public ActionResult Create()
{
return View();
}
for comparison here is an edit action in the same controller
public ActionResult Edit(int id = 0)
{
dbCounty countys = db.Countys.Find(id);
if (countys == null)
{
return HttpNotFound();
}
return View(countys);
}
I've also tryed adding this code to the create new actionlink wich is when i get this error
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Most likely causes:
The directory or file specified does not exist on the Web server.
The URL contains a typographical error.
A custom filter or module, such as URLScan, restricts access to the file.
What am i doing wrong here ....
My project is build on a hierachy model, One Client Many Countys ( if you need more code let me know )
thanks in advance.
Tip:
there must be a reason ( my assumption ) why when removing this line of code it works ( so it must be this line of code ?? ) - must be a different way of passing it ( clientID does have a value of 1 )
#Html.ActionLink("Back to List", "Index", new { id=Model.ClientID})
Edit Index Controller needed :
public ActionResult Index([Bind(Prefix="id")] int CID=0)
{
var clnt = db.Clients.Find(CID);
if (clnt != null)
{
return View(clnt);
}
return HttpNotFound();
}
EDIT: new create action from Countys Controller
public ActionResult Create(int id=0)
{
dbCounty countys = db.Countys.Find(id);
if (countys == null)
{
return HttpNotFound();
}
return View(countys);
}
i have also tryed running
public ActionResult Create(int id=0)
{
dbClient Client = db.Clients.Find(id);
if (Client == null)
{
return HttpNotFound();
}
return View(Client);
}
( since i am passing a clientID - the way the models are built it should add a county id while creating this new row in the database with the clientID(passedVariable)
You don't seem to be passing a model to the Create view. In your Create controller, you need something like the following, where Client is an object that has the property ClientID.
public ActionResult Create()
{
...
return View(Client);
}
EDIT:
To clarify, in your Create View, the Model is null, because you didn't pass it one in the controller. Take a look at the controllers that work, and see what it's passing to the View. You'll need to do something similar for Create.
I will try to sum up your problem. You said that if you remove
#Html.ActionLink("Back to List", "Index", new { id=Model.ClientID})
There is no errror, and the error happens when your view is generating. This two facts means that in 99% your Model is null
Check that in
#Html.ActionLink("Back to List", "Index", new { id=Model.ClientID})
Model is not null, otherwise you will get null reference exception
I have a strongly typed view
#model IEnumerable<MagazineIndex>
that represents user input array of objects.Also I have a dropdown:
#Html.DropDownList("DropDownName",
(List<SelectListItem>)ViewData["magazines"],
new { id = "DropDownName" })
When I submit form I get this error:
There is no ViewData item of type 'IEnumerable' that has the key 'DropDownName'.
My controller is like this:
public ActionResult CreateContent(IList<MagazineIndex> indexes,
string DropDownName)
How must I correct bind values?
Make sure that in your HttpPost action you are populating the ViewData["magazines"] the same way you did in your Get action:
[HttpPost]
public ActionResult CreateContent(IList<MagazineIndex> indexes, string DropDownName)
{
...
ViewData["magazines"] = ... same stuff as in your GET action
return View(indexes);
}
This is only necessary to be done if you intend to redisplay the same view in your POST action. If you redirect, you don't need it. The reason you need it is more than obvious. Your view needs to render a DropDown control which depends on its value.
I have a simple Action in my Controller:
public ActionResult Edit(int itemId)
{
return View(new EditModel() { ItemId = itemId + 1 });
}
public class EditModel
{
public int ItemId { get; set; }
public string Title { get; set; }
}
The problem comes in the View, when I try to display everything.
Model.ItemId: #Model.ItemId
#Html.EditorForModel()
Since action parameter and property on EditModel have the same name (itemId) I get the following:
Is this a correct behaviour? How can I change default value displayed inside a form in that case?
This may be somehow confusing for the first look, but yes, this is default(correct) behavior. Controller.ModelState is the privileged supplier for the values when you use EditorFor or similar editor helpers, over the model itself. But there's trickier point in your situation.
ModelState is populated with action parameters and values that take part in model binding. When you call that action, ModelState is populated with "ItemId" = action parameter(itemId) value. Later, EditorFor sees that is should draw editor for ItemId. As ModelState has already got ItemId, it does not look at model value, but extracts it from ModelState["ItemId"]. Tricky source of your error is that action parameter name matches the model property name and modelState prefers that over model value. The best solution (clean one) would be to just rename action parameter, so that it does not match the model property name.
public ActionResult Edit(int initialItemId)
{
return View(new EditModel() { itemId = initialItemId + 1 });
}
This will do the trick.
You can write
Model.ItemId: #Model.ItemId
#Html.EditorFor(x => x.Title)
Or hide ItemId for edit with metadata