asp.net mvc 3 remote attribute passing 3 fields - asp.net-mvc-3

I want to pass three field to my controller using RemoteAttribute. How can i do it?
public int ID1 { get; set; }
public int ID2 { get; set; }
[Remote("CheckTopicExists", "Groups", AdditionalFields = "ID1", ErrorMessage = " ")]
public string Topic { get; set; }
public ActionResult CheckTopicExists(string topic, int ID1,int ID2)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
How can i pass three field to that function?

You could separate them by comma:
AdditionalFields = "ID1, ID2"
Full example:
Model:
public class MyViewModel
{
public int ID1 { get; set; }
public int ID2 { get; set; }
[Remote("CheckTopicExists", "Home", AdditionalFields = "ID1, ID2", ErrorMessage = " ")]
public string Topic { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
ID1 = 1,
ID2 = 2,
Topic = "sample topic"
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
public ActionResult CheckTopicExists(MyViewModel model)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
View:
#model MyViewModel
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.ID1)
#Html.EditorFor(x => x.ID2)
#Html.LabelFor(x => x.Topic)
#Html.EditorFor(x => x.Topic)
#Html.ValidationMessageFor(x => x.Topic)
<input type="submit" value="OK" />
}

Be aware of sending dates, sometimes controller receive date in a wrong format: was dd/mm/yyyy, receive mm/dd/yyyy

Instead of using
public ActionResult CheckTopicExists(MyViewModel model)
If you use
public ActionResult CheckTopicExists(FormCollection Collection)
then you can reuse the code for other classes as well

Related

How do you send data to controller with ajax.beginform?

This is my method on controller "sale"
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Models.account account)
{
Models.sale creaventa = new Models.sale();
//creaventa.account = cliente;
creaventa.createdon = DateTime.Now;
creaventa.idaccount = account.id;
creaventa.modifiedon = DateTime.Now;
creaventa.status = 0;
context.sales.Add(creaventa);
context.SaveChanges();
// return "venta creada";
return View();
}
and this is the partial view
#model List<modal3.Models.account>
#{
ViewBag.Title = "Create";
}
<select class="form-control" id="control1">
#{
foreach (var cliente in Model)
{
<option value="#cliente.id"> #cliente.name</option>
}
}
</select>
#*#using (Html.BeginForm("create", "sale", FormMethod.Post, new {id="my-form" }))
{
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-default" value="Create" id="btncrear">
Iniciar Venta
</button>
}*#
#using (
Ajax.BeginForm("create","sale",new AjaxOptions()
{
HttpMethod ="Post",
InsertionMode = InsertionMode.Replace,
})
)
{
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-default" value="Create" id="btncrear">
Iniciar Venta
</button>
}
This does enter to method with this does not send the model.
Then:
How to send a model?
How to send a lot of objects?
this is my model
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace modal3.Models
{
using System;
using System.Collections.Generic;
public partial class sale
{
public sale()
{
this.saledetails = new HashSet<saledetail>();
}
public int id { get; set; }
public Nullable<System.DateTime> createdon { get; set; }
public Nullable<System.DateTime> modifiedon { get; set; }
public Nullable<int> status { get; set; }
public Nullable<int> idaccount { get; set; }
public virtual account account { get; set; }
public virtual ICollection<saledetail> saledetails { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace modal3.Models
{
[MetadataType (typeof (sale_validation ))]
public partial class sale
{
}
public class sale_validation
{
//2015-06-17 22:07:26.353 2015-06-17 22:07:26.353 1 1
[Display (Name="")]
[HiddenInput (DisplayValue =false )]
public Nullable<System.DateTime> createdon { get; set; }
[Display(Name = "")]
[HiddenInput(DisplayValue = false)]
public Nullable<System.DateTime> modifiedon { get; set; }
[Display(Name = "")]
[HiddenInput(DisplayValue = false)]
public Nullable<int> status { get; set; }
public Nullable<int> idaccount { get; set; }
}
}
To make you understand how AJAX FORM works, I created below code -
Lets say our model -
public class Sale
{
public string SaleOwner { get; set; }
public virtual Account Account { get; set; }
}
public class Account
{
public string Name { get; set; }
}
I created two controller actions -
public ActionResult adatas()
{
return View();
}
[HttpPost]
public JsonResult Create(Sale s)
{
return Json("true");
}
The first controller action return following view -
#model WebApplication1.Controllers.Sale
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#using (Ajax.BeginForm("Create", "Sale", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "done"
}))
{
#Html.TextBoxFor(m => m.SaleOwner)
#Html.TextBoxFor(m => m.Account.Name)
<input type="submit" value="click" />
}
<div id="done">
</div>
View Renders as follows -
Once we click on button, with breakpoints in the code -
Once AJAX POST happens, output would be -

Encounter Error for generating Radio button from Model

i am trying to generate radio button from model but getting object reference error. i just can not understand where i am making mistake in MVC because i am just learning it. here is my full code. please have a look and tell me where is the mistake. thanks
model class
public class StudentModel
{
[Required(ErrorMessage = "First Name Required")] // textboxes will show
[Display(Name = "First Name :")]
[StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name Required")] // textboxes will show
[Display(Name = "Last Name :")]
[StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Sex Required")]
[Display(Name = "Sex :")]
public int SexID { get; set; }
public List<Sex> Sex { get; set; }
}
public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}
controller class
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var student = new StudentModel
{
FirstName = "Rion",
LastName = "Gomes",
//I think the best way to populate this list is to call a service here.
Sex = new List<Sex>
{
new Sex{ID="1" , Type = "Male"},
new Sex{ID="2" , Type = "Female"}
}
};
return View();
}
[HttpPost]
public ActionResult Index(StudentModel model)
{
if (ModelState.IsValid)
{
//TODO: Save your model and redirect
}
//Call the same service to initialize your model again (cause we didn't post the list of sexs)
return View(model);
}
}
view code
#model MvcRadioButton.Models.StudentModel
#Html.BeginForm()
{
<div>
#Html.LabelFor(model => model.FirstName)
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div>
#Html.LabelFor(model => model.LastName)
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
#{
foreach (var sex in Model.Sex)
{
<div>
#Html.RadioButtonFor(model => model.Sex, new { id = "sex" + sex.ID })
#Html.Label("sex" + sex.ID, sex.Type)
</div>
}
}
<input type="submit" value="Submit" />
}
this line throwing error
foreach (var sex in Model.Sex) saying model null or object reference error
You never return a model to your view when the page is initially served. As a result, when you try to iterate over the Sex object you get the null reference error.
[HttpGet]
public ActionResult Index()
{
... code ...
return View(); //The problem is here!
}
You should be returning a model to your view:
[HttpGet]
public ActionResult Index()
{
... code ...
return View(student);
}

No view updating after viewmodel been changed

can't find whats wrong and can't find answer anywhere. My problem is my view not updated after view model have bean changed
ViewModel:
public class OrderView
{
public Customer Customer { get; set; }
public Order Order { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
public List<string> DomenNames { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
}
Controller:
private OrderView ov;
public ActionResult Index()
{
return View(ov);
}
[HttpPost]
public ActionResult Index(OrderView model, FormCollection collection) {
return View("done");
}
public ActionResult BlankEditorRow(OrderView model) {
ov = model;
ov.Order.DomenNames.Add("");
return View("Index",ov) ;
}
View:
#using (Html.BeginForm("Index","Order",FormMethod.Post, new {id = "createOrder"})) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Order</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Order.DomenNames)
</div>
#for(int i = 0; i < Model.Order.DomenNames.Count; i++) {
<div>
#Html.EditorFor(item => item.Order.DomenNames[i])
</div>
}
<button type="button" id="b1" onclick="setallert()" >Click me</button>
...
and script:
<script type="text/javascript">
function setallert() {
$.ajax({
url: "Order/BlankEditorRow",
data: $('#createOrder').serialize(),
cache: false,
success: function (data) {
...?
}
});
};
</script>
it goes fine to pass model to controller and while debugging through view I can see that model is changed, but in some case it nothing happen in view. It looks like old model is in place.
I have solved my problem. I post my solution in case some one need it:
Controller:
public ActionResult BlankEditorRow(OrderView model) {
model.Order.DomenNames.Add("");
return PartialView("Index", model) ;
}
View:
<div class="editor-label">
#Html.LabelFor(model => model.Order.DomenNames)
</div>
<div id="tt">
#{Html.RenderPartial("OrderDN", this.Model);}
</div>
<button type="button" id="addBtn">Click me</button>
Script:
$("#addBtn").click(function () {
$.get('#Url.Action("BlankEditorRow", "Order")', $('#createOrder').serialize(), function (res) {
document.getElementById("tt").innerHTML = res;
});
})
I hope it will be useful to someone

WebGrid MVC 3 with RadioButton Get Selected

how I can make the WebGrid as appears in the picture and get the selected row with the rariobutton
Blessings
Try this
myGrid.Column(header: "Select", format: #<text><input name="chck"
TYPE="RADIO" CHECKED="#item.select" /></text>),
Also check this link http://fiddle.jshell.net/Gt4GH/
This is not a compiled code, try this and let me know if it works :)
You could define view models:
public class UserViewModel
{
public int Id { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class MyViewModel
{
public int? SelectedUserId { get; set; }
public IEnumerable<UserViewModel> Users { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var users = Enumerable.Range(1, 5).Select(x => new UserViewModel
{
Id = x,
Email = "email " + x,
FirstName = "fn " + x,
LastName = "ln " + x,
});
var model = new MyViewModel
{
Users = users
};
return View(model);
}
[HttpPost]
public ActionResult Index(int? selectedUserId)
{
return Content(string.Format("Thank you for selecting user id: {0}", selectedUserId));
}
}
and finally a view:
#model MyViewModel
#{
var grid = new WebGrid(Model.Users);
}
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column(
header: "Select",
format: #<text>#Html.RadioButtonFor(x => x.SelectedUserId, (int)item.Id)</text>
),
grid.Column("Email"),
grid.Column("FirstName", "First Name"),
grid.Column("LastName", "Last Name")
)
)
<button type="submit">OK</button>
}

How to make dropdownlist

How make a dropdownlist? [Edited - almost working code]
View:
<div class="editor-label">
Firma
<div class="editor-field">
#Html.DropDownListFor(x => x.ID_firma, Model.firmaList)
#Html.ValidationMessageFor(model => model.nazwa)
</div>
Model:
public class produktModel
{
[Required(ErrorMessage="Proszę podać nazwę.")]
public string nazwa { get; set; }
[Required(ErrorMessage = "Proszę podać ilść produktu.")]
public decimal ilosc { get; set; }
[Required(ErrorMessage = "Proszę podać jednostkę produktu (np. kg, l, szt.).")]
public string jednostka { get; set; }
[Required(ErrorMessage = "Proszę podać cenę produktu.")]
public decimal cena { get; set; }
public string ID_firma { get; set; }
public IEnumerable<SelectListItem> firmaList { get; set; }
}
Controller:
public ActionResult dodaj()
{
var firma = baza.Firmas;
var model = new produktModel
{
firmaList = firma.AsEnumerable().Select(x => new SelectListItem
{
Value = x.ID_firma.ToString(),
Text = x.nazwa
})
};
return View(model);
}
[HttpPost]
public ActionResult dodaj(produktModel model)
{
Produkt prod = new Produkt();
prod.nazwa = model.nazwa;
prod.ilosc = model.ilosc;
prod.jednostka = model.jednostka;
prod.cena = model.cena;
prod.ID_firma = model.ID_firma;
baza.Produkts.InsertOnSubmit(prod);
baza.SubmitChanges();
return RedirectToAction("zarzadzaj_produktami", "Produkt");
}
It almost work...
I have only one problem (I hope)...
Value is string, and I save his value to database... (I don't now how to write it...)
prod.ID_firma = model.ID_firma;
prod.ID_firma is int. model.ID_firma is this value which is string. So I have an error:
Error 1 Cannot implicitly convert type 'string' to 'int?'
change your model a bit, i have assumed the column names change them according to your code
public class produktModel
{
[Required]
public string name { get; set; }
public decimal price { get; set; }
[Required]
public int companyID {get; set;}
public List<Company> compList {get; set;}
}
public class Company{
public int CompanyID {get;set;}
public string CompanyName {get;set;}
}
ActionResult should look like
public ActionResult add()
{
produktModel model = new produktModel();
model.compList= (from b in base.Companies
select new Company{
CompanyID = b.CompanyID,
CompanyName = b.CompanyName
}).ToList();
return View(model);
}
in your (strongly typed) view
#model produktModel
....
<div class="editor-label">
Company
<div class="editor-field">
#Html.DropDownListFor(model => model.companyID,
new SelectListItem(model.compList,
"CompanyID ",
"CompanyName "))
#Html.ValidationMessageFor(model => model.company_name)
</div>
...
Your question isn't clear enough.
Any way you can use the telerik combox\dropdown list or the default mvc dropdown list. you can find a lot of examples on google for that.
With Telerik write something like this:
#(Html.Telerik().ComboBox()
.Name("ComboBox")
.BindTo(new SelectList("CompanyID", "CompanyName")))
see this Telerik demo for more information.

Resources