How to pass parameter to sitecore controller rendering method - c#

I have this on my cshtml page
<div class="liveMatch-timer">
#Html.Sitecore().Controller("Blog", "LiveBlogHeader")
</div>
And this is my controller
public PartialViewResult LiveBlogHeader()
{
var matchHeader = GetMatchDayHeader();
return PartialView(BlogConstant.LiveBlogHeaderPath, matchHeader);
}
I have one hidden field with the name "liveMatchItemId" on my cshtml page. I would like to pass its value to controller so that I can access it inside controller. I am expecting to change controller definition something like this
public PartialViewResult LiveBlogHeader(string liveMatchItemId)
Anyone can help me understand on how can I do this? I am new to sitecore and MVC.
EDIT: I am able to achieve this using below code
#Html.Action("LiveBlogHeader", "Blog", new { liveMatchItemId = "12" })
But how can I set hidden field value instead of static field "12"?

Probably you could use something like:
#Html.Action("LiveBlogHeader", "Blog", new { liveMatchItemId = Model.LiveMatchItemId })
Where Model.LiveMatchItemId is the property that you want to pass to the controller.

Related

Assigning a value to the Controller depending on a link being click

I have a website with two forms one for inHole and the other Surface. The forms are identical but I would like to know where did the user clicked so I can assign a value to my SureyLocationID in the controller so I can refer to it later in my database if I need to without creating 2 views. Is there a way of doing so?
You can use Query string to pass a parameter with your link like :
http://example.com/over/there?sureyLocationID=inHole
or
http://example.com/over/there?sureyLocationID=Surface
So you just have to check the URL and retrieve the information you pass through it
In your MVC view have a button or anchor tag like this:
<a href='#Url.Action("YOUR_ACTION_NAME", "YOUR_CONTROLLER_NAME", new { comingFromInHole = true } )'>NAME_FOR_THIS_ELEMENT</a>
or
<input type="button"
onclick="location.href='#Url.Action("YOUR_ACTION_NAME", "YOUR_CONTROLLER_NAME", new { comingFromInHole = true} )'"
value="NAME_FOR_THIS_ELEMENT"/>
And in you MVC Controller:
public IActionResult YOUR_ACTION_NAME(bool comingFromInHole)
{
if (comingFromInHole)
{
// logic related coming from hole
}
else
{
// Logic related to surface
}
}
If you don't want to use boolean true or false, then you could use enumeration (or your custom defined type..etc) and use that as well:
public enum Types {InHole, Surface };
Then controller action signature will be changed to take in Types enum
public IActionResult YOUR_ACTION_NAME(Types type)
and modify your button or anchor link to send enum type to controller as below:
<a href='#Url.Action("YOUR_ACTION_NAME", "YOUR_CONTROLLER_NAME", new { Types=HomeController.Types.InHole} )'>NAME_FOR_THIS_ELEMENT</a>

Get RadioButton Value KnockoutJs

I have dynamically created radio buttons in my view and i am trying to pass the checked value to my controller. When my controller is hit the Agentcode string is Empty and i cant figure out how to grab the value so i can send it to my controller.
EDIT my radio buttons are generated in a foreach which i think may be causing the difficulty in reaching the value.
This is what the html rendered by the MVC control looks like
<div>
<input name="XXXXX" type="radio" value="{ data_bind = checkedValue: $data,checked: $root.AgentCode }">
</div>
foreach (var code in Model.ActiveAgentCodes)
{
<div>
#Html.RadioButton(code.AgentCode, new { data_bind="checkedValue: $data,checked: $root.AgentCode"})
#Html.RadioButton(code.AgentCode, new {data_bind="checkedValue: $data,checked: $root.AgentCode"}) }
my knockout ViewModel looks like this.
function ViewModel(){
var self = this;
self.AgentCode = ko.observable();
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
and the post method in my controller looks like this
[HttpPost]
public ActionResult GetAgentCodeForHomeController(string AgentCode)
{
return RedirectToAction("Home", "Home");
}
In my view i am posting using like so
#using (Html.BeginForm("GetAgentCodeForHomeController", "ChangeAccount"))
{
#Html.RadioButton(code.AgentCode, new {data_bind="checkedValue: $data,checked: $root.AgentCode"})
#Html.HiddenFor(model => model.AgentCode, new { data_bind = "text:AgentCode" })
}
<button type="submit">OK</button>
I needed to send data back to my controller and the best way that i found was to add properties to my viewmodel.
public string AgentCode {get; set;}
Then give the radio buttons an Id so that when the controller is hit MVC maps the properties correctly. I decided to not go with knockout and instead post the form back to the controller. It ended up looking like this on my buttons.
#Html.RadioButton("AgentCode", code.AgentCode, new {id = code.AgentCode})

MVC C# PagedList - PagedListPager passing parameters

I have a paged list using unobtrusive ajax that looks like this.
#Html.PagedListPager(Model, page => Url.Action("Images", "Admin", new { imageLibrary = image.ImageLibrary, page }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions()
{ InsertionMode = InsertionMode.Replace, UpdateTargetId = "imagesContainer" }))
My controller looks like this:
public ActionResult Images(ImageModels image, int? page, string imageLibrary)
{
// do stuff here
}
I was trying to pass a model to my controller, so instead of imageLibrary = image.ImageLibrary, I should have only needed to pass image = imageModel, but when I pass the model itself, the controller gets a null value (yes the model name was spelled correctly). When I try to get a property of the model and pass it to the controller (that's the imageLibrary = image.ImageLibrary) the controller receives both the model and the imageLibrary string value! This works fine for the end result, I just don't understand why it works, and I shouldn't have to pass the string value imageLibrary to my controller - especially if I'm not really using it.
Any insight on this would be appreciated.

Retaining route details on MVC Form Postback

I have a basic MVC form which is accessed through a GET Action with 3 string parameters pulled from the route.
[HttpGet]
public ActionResult Application(string x, string y, string z)
{
//create model, setup form, etc...
return View(model);
}
The route to access this form is configured as follows:
routes.MapRoute("Application",
"application/{x}/{y}/{z}",
new
{
controller = "Application",
action = "Application",
x = "",
y = "",
z = ""
});
And the form is configured as follows:
Html.BeginForm("Application", "Application", FormMethod.Post)
All of this works until I click submit on the resulting form. From a routing perspective the correct POST Action is called and the Model is bound correctly. The problem is I have lost all the x/y/z route information which I still need. How can I preserve the route information?
I've tried a couple things:
Added route details to the Form in Hidden fields which are added to the form content correctly but never get returned in the Model on postback
Tried using the RouteValueDictionary overload for Html.BeginForm but can't figure out how to make it work. I may just need a proper example of how to use it and how to access the state from the Controller
Update: This adds View sample to help address comments made regarding the use of Hidden Fields
#using (Html.BeginForm("Application", "Application", FormMethod.Post, new
{
autocomplete = "on",
id = "LoanApplication",
novalidate = string.Empty,
name = "Application"
}))
{
<fieldset>
#Html.HiddenFor(m => m.x)
#Html.HiddenFor(m => m.y)
#Html.HiddenFor(m => m.z)
#Html.HiddenFor(m => m.DigiCertId)
<br />
<input id="SubmitButton" type="submit" value="#Resources.SubmitApplicationButton" title="#Resources.SubmitApplicationButtonDescription" />
</fieldset>
}
You should really put these properties in the model, then have a HiddenFor for each one, like so:
#Html.HiddenFor(m => m.x)
#Html.HiddenFor(m => m.y)
#Html.HiddenFor(m => m.z)
Then in your post method (assuming it's like this), you can pass them in the RouteValueDictionary to the Get Method, like so:
[HttpPost]
public ActionResult Application(MyModel model) //whatever type your model is
{
//do whatever your post method does before redirect
return RedirectToAction("Application", new { x = model.x, y = model.y, z = model.z});
}
in addition to the ans suggested by mattytommo. i would recommend using TempData collection in asp.net MVC. this saves the data using the session storage but does it temprorarily and the data gets deleted once you access it.
this is present specifically for these purposes
so you can save the data in TempData as TempData["Values"] = new {X=x,Y=y,Z=z};
then access the TempData["Values"] after the post

Asp.net MVC 2: Can Ajax.ActionLink pass a parameter without it going into the url?

I have the following in partial view
<%= Ajax.ActionLink("Plunder Again", "Resources", new { controller = "Resource", parent = Model.ToJson() }, new AjaxOptions { UpdateTargetId = Model.ResourceType })%>
going to the controller method:
public ViewResult Resources(/*ModelResource parent*/)
{
Debug.Assert(Request.Params["parent"]!=null);
var jss=new System.Web.Script.Serialization.JavaScriptSerializer();
var parent=jss.Deserialize<ModelResource>(Request.Params["parent"]);
return View(parent.PlunderAmount);
}
but it throws an exception because the json doesn't properly pass via url, it can't find the 'Type' parameter.
I tried simply having the ModelResource as a parameter to the Action but it came in as null
This action will also be returning a partial view if that matters in any way.
ActionLink is used to create an anchor to a URL -- the URL must be valid! In general, you don't pass a whole object to an Action because the route values have to be bound back into the model and passed to the action. You might pass an ID of object though so the Action can get the object using that key.
If you want to send Model to controller instead of Ajax.ActionLink use Ajax.BeginForm

Categories

Resources