jquery - Ajax form with different actions in ASP MVC -
in asp.net mvc have following input form (simplified):
<div id="ajaxtarget"> @using (ajax.beginform("submitform", "home", new ajaxoptions { updatetargetid = "ajaxtarget" })) { @html.dropdownlistfor(x => x.postalcode, model.postalcodeitemlist, new { @name = "postalcodeid" , @id="postalcodeid" }) @html.labelfor(x => x.streetcode) @html.dropdownlistfor(x => x.streetcode, model.streetitemlist, new { @id="streetcodeid" }) ... <input type="submit" value="@global.execute" id="btnsubmit" /> } </div>
when user selects first dropdownlist, second dropdownlist should populated via ajax. can send 'call' controller via javascript update view:
$(document).ready(function () { $('#postalcodeid').on('change', function () { $(this).parents('form').submit(); }); });
my problem form has lot of different controls trigger action need handle in controller, i'm looking way add parameters when submit form.
right found solution add field in model , in form populate in javascript depending on control fires script. @html.hiddenfor(x => x.chosencontrolleraction, new { id = "chosenaction" })
in controller can return view or action based on value:
public actionresult submitform(mymodel model) { if (model.chosencontrolleraction == "populatestreetcodes") { ... }
i'm sure there must different/better way archieve want do. what's right way return correct actionresults in complex self updating ajax form?
the proper way create 1 method each action want in controller. , should have 1 javascript code each of these actions.
example :
controller
public actionresult populatefirstdropdown(mymodel model) { // return new values first dropdownlist // or partial view } public actionresult populateseconddropdown(mymodel model) { // return new values second dropdownlist // or partial view } public actionresult submitform(mymodel model) { // save form }
javascript :
$('#firstfield').on('change', function() { $.ajax({ url: "/yourcontroller/populatefirstdropdown", type: "post", data: $(this).closest('form').serialize(), success: function (data) { // use data refresh dropdownlist // or refresh content of partial view }, }); }); $('#otherfield').on('change', function() { $.ajax({ url: "/yourcontroller/populateseconddropdown", type: "post", data: $(this).closest('form').serialize(), success: function (data) { // use data refresh dropdownlist // or refresh content of partial view }, }); });
let me know if answer not clear enough.
Comments
Post a Comment