I am using asp.net MVC framework. On my page i have a dropdwonbox and when an option is clicked i want to go to another page. But i can't find how/where to set the autopostback property to true. This is the code i'm using:
Aspx:
<%= Html.DropDownList("qchap", new SelectList( (IEnumerable)ViewData["qchap"], "Id", "Title" )) %>
Controller:
public ActionResult Index(int id)
{
Chapter c = new Chapter();
ViewData["qchap"] = c.GetAllChaptersByManual(id);
return View();
}
What do i have to do to use the autopostback functionality?
You can use the onchange client event:
<%= Html.DropDownList("qchap",
new SelectList( (IEnumerable)ViewData["qchap"], "Id", "Title" ),
new { onchange = "this.form.submit();" }) %>
It seems the DropDownList helper method doesn't support this.
Maybe using it within a form and a custom custom html attribute to submit the form do it.
I believe too that you may want to adjust your postback to the formsCollection
postback public ActionResult Index(FormsCollection myform)
(I'm not on my home pc where MVC is installed, so I can't verify the syntax here)
I solve using this code.
Function Index(ByVal collectionField As FormCollection) As ActionResult
Dim industryCategoryID As Long = collectionField.Item("ddlIndustry")
If industryCategoryID = 0 Then
Me.ViewData("IndustryList") = GlobalController.GetIndustryList
Return View(_service.ListCompanies())
Else
Me.ViewData("IndustryList") = GlobalController.GetIndustryList
Return View(_service.ListCompanies(industryCategoryID))
End If
End Function
That's for the ActionResult function
And Then for the View
<p>
<% Using Html.BeginForm()%>
<%=Html.DropDownList("ddlIndustry", New SelectList(CType(ViewData("IndustryList"), IEnumerable), "ID", "Name"), "--Choose industry--", New With {.onchange = "this.form.submit()"})%>
<% End Using %>
</p>
I hope it helps. I f you would like more complete codes please feel good to email me at boylevantz#gmail.com
Related
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})
I'm using asp.net mvc 2 and i found this behavour which i can't understand.I have following view:
<% using (Html.BeginForm("Index", "BlackListGrabber", FormMethod.Post) )
{
<%= Html.DropDownListFor(m => m.selectedArea, new SelectList(Model.areaList, "value", "text")) %>
<% if (Model.districtList != null) { %>
<%= Html.DropDownListFor(m => m.selectedDistrict, new SelectList(Model.districtList, "value", "text")) %>
<% } %>
<% if (Model.townList!= null) { %>
<%= Html.DropDownListFor(m => m.selectedTown, new SelectList(Model.townList, "value", "text")) %>
<% } %>
<input type="submit" value="post" />
<% } %>
and a controller's method like this:
[HttpPost]
public ActionResult Index(BlackListGrabberModel postedModel)
{
BlackListGrabberModel model = new BlackListGrabberModel(postedModel);
return View(model);
}
And, last but not least, my model:
BlackListGrabberModel(BlackListGrabberModel model)
{
if (string.IsNullOrEmpty(model.selectedArea))
{
areaList = GetRegions();
}
else if (string.IsNullOrEmpty(model.selectedDistrict))
{
areaList = model.areaList;
districtList = GetRegions(model.selectedArea);
}
else if (string.IsNullOrEmpty(model.selectedTown))
{
areaList = model.areaList;
districtList = model.districList;
districtList = GetRegions(model.selectedDistrict);
}
}
Idea is that then i load page, i see list of all possible areas.(And i see it - it's my first dropdownlistfor) When i select area, after clicking "post" button, i see list of all districts, they loaded from external source and this part works fine.
So i select district from list, and click "post". After thar i see list of all towns located in selected district, but districtList disappears. Then i traced it in my controller, i found that property postedModel.districtList is null. But postedModel.areaList is fine! Does that mean that i can post only one SelectList, or i'm missing something? Can somebody please give me any help?
P.S. Properties "selectedArea", "selectedDistrict", "selectedTown" are posted as expected.
EDIT. Thanks to everybody, i missed some important things, and you gave me direction to them.
My problem appeared to be areaList. It was filled by default constructor. I forgot about that, so then i saw postedModel.areaList filled, i thought it was magically posted by asp.net mvc mechanisms, and complained that all other lists are not filled because of some strange glithces.
You will have to repopulate your list properties in your model for every request.
The won't get posted back automatically. Just the selected value is posted back and bound to the property in your model (i.e. selectedArea is bound but not areaList).
The lists should not post, only the values of the select elements in your html form will. If you need to hold onto the list values, you might try placing them in TempData in you GET for Index, which will keep them for the next request.
I'm using MVC and AJax.BeginForm to do some ajax updating of my page. The BeginForm code looks something like:
using (Ajax.BeginForm("HandleCrop", "Card",
new
{
accept = true,
id = Model.ImageUpload.ID,
file = Model.ImageUpload.File,
imageCropX = Model.CropInfo.X,
imageCropY = Model.CropInfo.Y,
imageCropWidth = Model.CropInfo.Width,
imageCropHeight = Model.CropInfo.Height
},
new AjaxOptions
{
HttpMethod = "POST",
OnComplete = "ConfirmCompleted",
OnSuccess = "ReloadUpload",
OnFailure = "Failure"
}, null))
The Model.CropInfo is being put in as hidden fields like so:
<%=Html.HiddenFor(m => m.CropInfo.X) %>
<%=Html.HiddenFor(m => m.CropInfo.Y) %>
<%=Html.HiddenFor(m => m.CropInfo.Width) %>
<%=Html.HiddenFor(m => m.CropInfo.Height) %>
However, these values are being dynamically modified by some client side javascript, and these values need to be posted through the Ajax call back to the server. The above code will obviously not work as the imageCrop.. parameters in the Ajax form are being filled when the page is rendered (therefore being all 0).
My question is: what is the correct way to approach this situation?
From Ajax this part should be absolutely removed:
imageCropX = Model.CropInfo.X,
imageCropY = Model.CropInfo.Y,
imageCropWidth = Model.CropInfo.Width,
imageCropHeight = Model.CropInfo.Height
With TryUpdateModel in the Action your CropInfo should be filled OK from posted data.
If you are NOT USING automatic update of the model (or via TryUpdateModel)
and instead of that you are USING this data as input parameters in Action then just rename these Action parameters to CropInfo_X, CropInfo_Y, CropInfo_Width and CropInfo_Height (I think this is how the hidden fields will be named in HTML, check this in page source)
Can someone help me out I'm new to jQuery, I would like to know how can I pass an object through from a controller action MVC
public ActionResult UserGroupSetting()
{
UserGroupSetting setting = //some code to retrieve the settings
ViewData["Theme"] = setting.Theme;
ViewData["Image"] = setting.LogoImage;
returnView(setting);
}
What I want its to get the Theme and the logo image, in a jQuery function, that I will use to update a class in a stylesheet, The theme object contains a colour in Hex form only for now.
If someone can please help me with the call to a jquery function and how will I expose both the image and the theme objects in jquery.. Thanks
You can return the data in jSon format and let jquery make a call to your action method with getJSON method
public ActionResult UserGroupSetting()
{
var result=new { Theme="YourTheme", Logo="YourLogoURL"};
return Json(result, JsonRequestBehavior.AllowGet);
}
In your page,Call this from your javascript
$(function(){
$.getJSON('YourController/UserGroupSetting', function(data) {
alert(data.Theme);
alert(data.Logo);
});
});
if i were you , i would do this:
you can use ViewBag: in action: ViewBag.Setting = setting;
UserGroupSetting setting = //some code to retrieve the settings
ViewBag.Theme = setting.Theme;
ViewData.Image = setting.LogoImage;
returnView(setting);
then in Razor:
#{
var setting = (UserGroupSetting)ViewBag.Setting;
}
output it to javascript tag:
<script type="text/javascript">
var setting = new setting{
Theme = #setting.Theme,
Image = #setting.Image
}
</script>
This may not be the best solution, but one option I've used in the past is to create a hidden input in your view and access the value of the input in your jQuery code. This would be an example of the code you would have in your view:
<input id="someID" type="hidden" value="#TempData["Theme"]" />
I have a code block in my MVC view as follows:
<%using (Ajax.BeginForm("MyAction", new { action = "MyAction", controller = "Home", id = ViewData["selected"].ToString() }, new AjaxOptions { UpdateTargetId = "Div1" }))
{ %>
<%=Html.DropDownList("ddl", ViewData["MyList"] as SelectList, new { onchange = "this.form.submit()" })%>
<%} %>
I want to set the value of ViewData["selected"] so that i can send it to the desired action.
Can anyone please suggest how can i do this?
thanks!
Instead of using a form, why not use a jQuery onChange event on your drop down?
$(document).ready(function() {
$("#ddl").change(function() {
var strSelected = "";
$("#ddl option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Home/MyAction/" + strSelected;
$.post(url, function(data) {
// do something if necessary
});
});
});
ViewData is not the place to pass data back to the server side. Values of html input controls within form tag are conveniently available in action method. You can get these values either from various types of action method arguments (model, formcollection etc).
Here is a link to free asp.net mvc ebook tutorial. Is a good resource for asp.net mvc.
Found solution at this post it is just small chnge
Yes, that’s right – only change is replacing:
onchange = “this.form.submit();”
with:
onchange = “$(this.form).submit();”