I have multiple check box values in a form. I am serializing the form and send to mvc controller as JSON data. How can i de-serialize the check box values?
This is my html -
#using (Html.BeginForm("SaveOfficeConfiguration", "Offices", FormMethod.Post, new { Id = "frmOfficeConfigSave" }))
{
<div id="divOfficeForm">
<div style="width: auto; height: auto; border: 3px outset silver;">
<table class="mainsectionable" width="100%">
<thead>
<tr>
<th style="text-align: center;">
<center>KCCM Profile Access</center>
</th>
</tr>
<tr>
<td>
#using (Html.BeginForm())
{
IEnumerable<SelectListItem> Brands = ViewBag.GetBrands;
foreach (var item in Brands)
{
#Html.CheckBox("KCCM_Brands", false, new
{
value = item.Value
});
<label>#item.Text</label><br />
}
}
</td>
</tr>
</thead>
</table>
</div>
</div>
}
This is my javascript function-
function SaveOfficeConfigNew() {
var officeID = $('input[name="hdnOfficeID"]').val();
var url = "/OfficeManagement/Offices/SaveOfficeConfiguration?officeID=" + officeID;
ShowWait();
$.ajax({
type: "POST",
url: url,
data: frmOfficeConfigSave.$('input').serialize(),
success: function (data) {
HideWait();
alert(data.msg);
},
error: function (data) {
HideWait();
alert(data.msg);
}
});
applyFilter();
return false;
}
This is my gonna be controller action -
[HttpPost]
public ActionResult SaveOfficeConfiguration(int ? officeID, FormCollection form)
{
try
{
*/..............
..............*/
return Json(new
{
success = true,
msg = String.Empty,
id = 1
}, JsonRequestBehavior.AllowGet);
}
catch (Exception error)
{
return Json(new
{
success = false,
msg = error.Message,
id = -1
}, JsonRequestBehavior.AllowGet);
}
}
You simply have to receive a List<string> parameter, with the same name you're giving the checkboxes, i.e., KCM_Brands. The Model Binder will deserialize it directly for you.
[HttpPost]
public ActionResult SaveOfficeConfiguration(int ? officeID, FormCollection form,
List<string> KCM_Brands)
{
....
}
To serialize your form data to post it, use the function suggedted in this post:
JSON object post using form serialize not mapping to c# object
You can use the FormsCollection to retrieve the check box values:
Controller:
[HttpPost]
public ActionResult SaveOfficeConfiguration(int ? officeID, FormCollection form)
{
var CheckBoxValues = form["KCCM_Brands"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x=>int.Parse(x));
}
For More info Have a look here :
http://www.mindstick.com/Articles/2ee905ba-aea1-4d83-a49d-d8d8fb10c747/?Checkbox%20control%20in%20MVC
Instead of
#Html.CheckBox("KCCM_Brands", false, new
{
value = item.Value
});
use this code to generate checkboxes
<input type="checkbox" name="KCCM_Brands" value="#item.Value" />
The action on your controller should look like this
public ActionResult SaveOfficeConfiguration(int? officeID, List<string> KCCM_Brands)
When you post your form, List<string> KCCM_Brands will be populated only with the values of selected checkboxes.
Also, I don't know if your javascript is correct, but I had to make the following change for it to work
data: $('#frmOfficeConfigSave input').serialize()
Related
I have a pop form AddorEdit.cshtml, which is called from index.cshtml page. The form is opening but unable to post data to controller method.
index page
// index.cshtml //
<a class="btn btn-success" style="margin-bottom:10px;" onclick="PopupForm('#Url.Action("AddorEdit", "Vehicles")')"><i class="fa fa-plus"></i> Add New</a>
<table id="tbl_vehicle" class="table table-striped table-bordered" style="width:100%;" >
//table block
<script>
function SubmitForm(form) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (date) {
if(data.success)
{
Popup.dialog('close');
dataTable.ajax.reload();
}
}
});
</script>
pop up form
//AddorEdit.cshtml //
#using (Html.BeginForm("AddorEdit", "Vehicles", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
//form
controller method
// VehiclesController.cs //
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddorEdit([Bind(Include = "Id,VehicleType,Amount,RenewPeriod,Status")] Vehicle vehicle)
{
if (ModelState.IsValid)
{
if (vehicle.Id <= 0)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
db.Vehicle.Add(vehicle);
}
else
{
db.Entry(vehicle).State = EntityState.Modified;
}
db.SaveChanges();
}
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
I am unable to detect why the data is not posting to the controller method. Thank You!!!
use like this in your Form,it will fix your problem
#using (Html.BeginForm("AddorEdit", "Vehicles", FormMethod.Post, new { onsubmit =
"return SubmitForm(this)" }))
{
#Html.AntiForgeryToken()
}
if you are using
[ValidateAntiForgeryToken]
this attribute on top of your action method
you must use
#Html.AntiForgeryToken()
in your view
I have created a table which dynamically generates records using the "Infinite Loading" process, I have a button in my HTML Code which i need to use to allow users to add the item in their favourite - so this is my HTML code
#model List<PagesAuth.Models.Links.MLink>
#foreach (var I in Model)
{
<tr>
<td class="v-align-top" id="itemcard">
<h4 class="card-title">
#I._title
<small><cite>#I._tp_created.ToString("dd MMM yyyy")</cite> /small>
</h4>
<div class="pull-right" id="options">
<ul class="list-inline text-right" >
#if (I._tp_favourite == 0)
{
<li><button class="btn-link glyphicon glyphicon-heart-empty" onclick="location.href='#Url.RequestContext .Action("_Fav", "Home", "#I._id")'"></button></li>
}
else
{
<li><button class="btn-link glyphicon glyphicon-heart-empty" onclick="location.href='#Url.RequestContext .Action("_UnFav", "Home", "#I._id")'"></button></li>
}
</ul>
</div>
</div>
</td>
</tr>
}
I am trying to use "Favourite" button to allow user to add that website to their favourite list (I am ok with the DB updates etc)
<ul class="list-inline text-right" >
#if (I._tp_favourite == 0)
{
<li><button class="btn-link glyphicon glyphicon-heart-empty" onclick="location.href='#Url.RequestContext .Action("_Fav", "Home", "#I._id")'"></button></li>
}
else
{
<li><button class="btn-link glyphicon glyphicon-heart-empty" onclick="location.href='#Url.RequestContext .Action("_UnFav", "Home", "#I._id")'"></button></li>
}
</ul>
What I want to know is how to achieve this on user front-end - Like I thought I should just create a PartialView and make it child action only in my controller, send it ID and do DB Processing
[ChildActionOnly]
public ActionResult _Fav(int ID)
{//Do DB Processing
return PartialView(ID);
}
First of all the following does not work
onclick="location.href='#Url.RequestContext .Action("_UnFav", "Home", "#I._id")'"
Second, if I end up making this work, it will still refresh the page and I don't want that.
Is there a better way to achieve this
Cheers
I don't know why you want to use partial views but you can do it this way.
Use ajax to send request to controller action.
Handle action result using JavaScript.
View:
#model List<PagesAuth.Models.Links.MLink>
#foreach (var I in Model)
{
<tr>
<td class="v-align-top" id="itemcard">
<h4 class="card-title">
#I._title
<small><cite>#I._tp_created.ToString("dd MMM yyyy")</cite> /small>
</h4>
<div class="pull-right" id="options">
<ul class="list-inline text-right" >
#if (I._tp_favourite == 0)
{
<li><button class="btn-link glyphicon glyphicon-heart-empty" onclick="Fav(#I._id)"></button></li>
}
else
{
<li><button class="btn-link glyphicon glyphicon-heart-empty" onclick="UnFav(#I._id)"></button></li>
}
</ul>
</div>
</div>
</td>
</tr>
}
JS:
Here I am just alerting that the favorite action succeeded, else you have an array of string errors to work with. You could redirect or do some stuff, whichever you prefer.
<script type="text/javascript">
function Fav(id) {
var url = '#Url.Action("_Fav", "Home")';
$.ajax({
url: url,
type: 'POST',
data: {
id: id
},
success: function (data) {
if(data.length == 0) // No errors
alert("Fave success!");
},
error: function (jqXHR) { // Http Status is not 200
},
complete: function (jqXHR, status) { // Whether success or error it enters here
}
});
};
function UnFav(id) {
var url = '#Url.Action("_UnFav", "Home")';
$.ajax({
url: url,
type: 'POST',
data: {
id: id
},
success: function (data) {
if(data.length == 0) // No errors
alert("Unfave success!");
},
error: function (jqXHR) { // Http Status is not 200
},
complete: function (jqXHR, status) { // Whether success or error it enters here
}
});
};
</script>
Controller:
[HttpPost]
public ActionResult _Fav(int ID)
{
List<string> errors = new List<string>(); // You might want to return an error if something wrong happened
//Do DB Processing
return Json(errors, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult _UnFav(int ID)
{
List<string> errors = new List<string>(); // You might want to return an error if something wrong happened
//Do DB Processing
return Json(errors, JsonRequestBehavior.AllowGet);
}
I have a page lets say Edit.cshtml in that page is a dropdownlist of item to updated. the loading of that page has no problem, the problem comes when I select an item on the dropdownlist and execute an ajax call.
$('#dDL').kendoDropDownList({
optionLabel: "Select",
dataTextField: "Value",
dataValueField: "Id",
dataSource: {
transport: {
read: '#Url.Action("GetItems", "BulkEdit")',
}
},
change: function (e) {
//this is where i call the '#Url.Action("GetMetaDataDetails", "BulkEdit")'
var test = getMetaDataDetails();
popupwindow.data("kendoWindow").open();
popupwindow.kendoWindow({
width: "600px",
title: "Mapping",
visible: false,
//modal: true,
animation: {
close: {
effects: "fade:out"
}
},
actions: [
"Pin",
"Minimize",
"Maximize",
"Close"
],
}).data("kendoWindow").center().open();
}
});
it goes through the controller with no issue, but it throws error if I return a view. Why?
this is my ajax call:
function getMetaDataDetails() {
return $.ajax({
type: "POST",
url: '#Url.Action("GetMetaDataDetails", "BulkEdit")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ itemTypeID: itemtypeID.toString() }),
dataType: "json",
success: function (data) {
debugger;
var checks = data;
},
error: function (data) {
debugger;
var check = data;
alert(result);
}
});
}
and this is my controller:
[HttpPost]
public virtual ActionResult GetMetaDataDetails(int itemTypeID)
{
var importProperties = GetImportColumnProperties(GetModel(itemTypeID));
var result = JsonConvert.SerializeObject(importProperties, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
ViewData["MetaDataModel"] = importProperties;
return Json(result, JsonRequestBehavior.AllowGet);
}
This is the pop-up window that should be populated after executing the getMetaDataDetails(), itemMetaData should have the values return by getMetaDataDetails()
#(Html.Kendo().Window()
.Name("itemwindow")
.Title("Item Mapping")
//.Modal(true)
.Content(#<text>
<table class="table table-bordered">
<thead>
<tr>
<th>Table Column</th>
<th>Excel Column</th>
</tr>
</thead>
#foreach (var props in itemMetadata.GetType().GetProperties())
{
var label = props.GetCustomAttribute<CanBulkUpdateAttribute>().CanBulkUpdate;
if (label == true)
{
var disp = props.GetCustomAttributes<DisplayPropertyName>();
<tbody>
<tr>
<td class="col-sm-3">
<label>
#disp.First().DisplayName
</label>
</td>
<td class="col-sm-3">
<select kendoDropDownList name="" id="ddlitem_#props.Name" style="width :250px;"></select><br>
</td>
</tr>
</tbody>
}
}
</table>
<button id="uploadAll" onclick="updatetable()" class="btn btn-primary">Update</button>
</text>)
//.Width(420)
.Height(440)
.Visible(false)
)
I need to use the return of GetMetadataDetails as model for my "popupwindow"
Hope you can help me.
I have a table with rss feeds and a button after each feed. When the user clicks the button I want to read the feed on the same page. I have everything working, except one thing. How do I send the url of the newsfeed back to the controller and then use it to show the news feeds, when the user clicks the button.
Here I show the urls of the newsfeeds in a table
<table class="table">
#{if (ViewBag.Rsslist != null)
{
foreach (var item in ViewBag.Rsslist)
{
<tr class="something">
<td class="col-md-2">
#item.sTidning
</td>
<td class="col-md-2">
#item.SUrl
#{string rssurl = item.SUrl; }
</td>
<td class="col-md-2">
Open
</td>
</tr>
}
}
else
{
<tr class="something">
<td class="col-md-2">No data to dsiplay</td>
</tr>
}}
</table>
Here i want to display the newsfeeds
<div class="col-md-4">
<table class="table">
<tr>
<td>
#{var inlast = reader.Las(ViewBag.Feed); }
#inlast.Title.Text
<br />
#inlast.Links[0].Uri<br />
#{foreach (var item in inlast.Items)
{
#item.Title.Text
<br />
}}
</td>
</tr>
</table>
Here is the line of code I tried above to accomplish my goal.
Open
What should I write instead? Here is my controller:
public class HomeController : Controller
{
private Rss_DevEntities _db = new Rss_DevEntities();
public ActionResult Index()
{
List<RSS_Head> rss_head = new List<RSS_Head>();
rss_head = _db.RSS_Head.ToList();
ViewBag.Rsslist = rss_head;
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Flasare()
{
return View();
}
}
}
Edit: Solution
I couldn't get the Ajax to work. I will have to look into Ajax more :) But I finally found a solution that works.
In my controller I created a method GettheFeed like this:
public ActionResult GettheFeed(string rssfeed)
{
List<RSS_Head> rss_head = new List<RSS_Head>();
rss_head = _db.RSS_Head.ToList();
ViewBag.Rsslist = rss_head;
ViewBag.Feed = rssfeed;
return View("~/Views/Home/Index.cshtml");
}
}
In my indexview I added this line of code
#Html.ActionLink("Open", "GettheFeed", new { rssfeed = rssurl })
Instead of
Open
And I finally got it to work after making sure that I checked if a variable is null instead of checking if a ViewBag is null in the code that displays the newsfeed.
You need to use Ajax
For example, fire this ajax when the user click on the button :
$.ajax({
url: '#Url.Action("getRssFeed", "Home")',
data: {rssurl = feedInfo}, //store the feed info in an attribute of your button for example
type: 'POST',
success: function(data) {
alert(data);
}
});
and with an getRssFeed function in your index controller :
[HttpPost]
public ActionResult getRssFeed(string rssurl)
{
ViewBag.Feed = rssurl ;
return View();
}
The alerted data will be the data you need to display. ( for example affect the data to your 'inlast' variable.
EDIT :
Your buttons in the loop will look like this, (based on ur code)
<a class="loadRss" id="#item.SUrl" class="btn btn-success btn-sm">Open</a>
And your js :
$(".loadRss").click(function() {
$.ajax({
url: '#Url.Action("getRssFeed", "Home")',
data: {rssurl : $(this).attr('id')},
type: 'POST',
success: function(data) {
}
});
});
And put the getRssFeed function above in your controler. I think what I wrote works, but it's ugly because your return your view (all the html, js ... etc) though you only need the modification of your model.
So I advise you to use partial views
Yes i agree with #kypaz , Use ajax which works fine without postback. You will get value of button.
You controller will be
public ActionResult Index(string rssurl)
{
List<RSS_Head> rss_head = new List<RSS_Head>();
rss_head = _db.RSS_Head.ToList();
ViewBag.Rsslist = rss_head;
return View();
}
In my MVC, i have a view and that contains one file upload control and one button.
<input type="file" id="Uploadfile" />
<input type="button" onclick()="GetFile();/>
Javascript function as follows
function GetFile()
{
var file_data = $("#Uploadfile").prop("files")[0];
window.location.href="Calculation/Final?files="+file_data;
}
I need to pass/send the selected file via fileupload control to controller in mvc.
i have the controller
public ActionResult Final(HttpPostedFileBase files)
{
//here i have got the files value is null.
}
How to get the selected file and send it to the controller?
Plz help me to fix this issue.
I had similar functionality to deliver in my project.
The working code looks something like this:
Controller Class
[HttpPost]
public ActionResult UploadFile(YourModel model1)
{
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength > 0)
{
string folderPath = Server.MapPath("~/ServerFolderPath");
Directory.CreateDirectory(folderPath);
string savedFileName = Server.MapPath("~/ServerFolderPath/" + hpf.FileName);
hpf.SaveAs(savedFileName);
return Content("File Uploaded Successfully");
}
else
{
return Content("Invalid File");
}
model1.Image = "~/ServerFolderPath/" + hpf.FileName;
}
//Refactor the code as per your need
return View();
}
View
#using (#Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table style="border: solid thin; margin: 10px 10px 10px 10px">
<tr style="margin-top: 10px">
<td>
#Html.Label("Select a File to Upload")
<br />
<br />
<input type="file" name="myfile">
<input type="submit" value="Upload" />
</td>
</tr>
</table>
}
you cannot send file content via javascript (unless HTMl5). and you are doing totally wrong. if you want to do HTML5 based solution via FileReader api then you need to check this out. FileReader Api
Just put a form tag and use the same name of the input in the controller action to perform model binding
#using(Html.BeginForm("yourAction","YourControl",FormMethod.Post))
{
<input type="file" id="fileUpload" />
}
then in controller.
[HTTPPost]
public ActionResult Final(HttpPostedFileBase fileUpload)
{
//here i have got the files value is null.
}
Below code will do a full post back in an hidden form which will give an illusion of ajax file upload. Try it:
Update:
JS
function Upload(sender) {
var iframe = $("<iframe>").hide();
var newForm = $("<FORM>");
newForm.attr({ method: "POST", enctype: "multipart/form-data", action: "/ControllerName/Final" });
var $this = $(sender), $clone = $this.clone();
$this.after($clone).appendTo($(newForm));
iframe.appendTo($("html")).contents().find('body').html($(newForm));
newForm.submit();
}
HTML
<input type="file" id="Uploadfile" name="Uploadfile" />
<input type="button" onclick="Upload($('#UploadFile'));"/>
Controller
public ActionResult Final(HttpPostedFileBase Uploadfile)
{
//here you can use uploaded file
}
As a completion from Ravi's answer, I would suggest to use the following using statement:
#using(Html.BeginForm("yourAction","YourControl",FormMethod.Post, new { enctype="multipart/form-data" }))
{
<input type="file" id="fileUpload" />
}
You can do it by using json data to view.
As instance,
Controller
public ActionResult Products(string categoryid)
{
List<catProducts> lst = bindProducts(categoryid);
return View(lst);
}
public JsonResult Productsview(string categoryid)
{
//write your logic
var Data = new { ok = true, catid = categoryid};
return Json(Data, JsonRequestBehavior.AllowGet);
}
View:
#{
ViewBag.Title = "Index";
}
#model ASP.NETMVC.Controllers.Categories
<h2>List Of Categories</h2>
#Html.ListBox("lst_categories", (IEnumerable<SelectListItem>) ViewBag.Categories)
<script type="text/javascript">
$(function () {
$('#lst_categories').change(function () {
var catid = $('#lst_categories :selected').val();
$.ajax({
url: '#Url.Action("Productsview", "Jquery")',
type: 'GET',
dataType: 'json',
data: { categoryid: catid },
cache: false,
success: function (Data) {
if (Data.ok) {
var link = "#Url.Action("Products", "Jquery", new { categoryid = "catid" })";
link = link.replace("catid", Data.catid);
alert(link);
window.location.href = link;
}
}
});
});
});
</script>