How can I save the data when I return to my action and retrieve it? - asp.net-mvc-3

I have a class and create an instance and fill a property in my index but when I push the submit button in my view and return again to my index action the property of my class is null.
How can I save the data when I return to my action and retrieve it? Is it possible?
I used viewbag and viewdata in my index and fill theme but when returned to index action again all of theme were null :(
public class myclass
{
public string tp { get; set; }
}
public class HomeController : Controller
{
//
// GET: /Home/
myclass myc = new myclass();
public ActionResult Index()
{
myc.tp = "abc";
return View(myc);
}
}
View:
#model MvcApplication2.Controllers.myclass
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
#using (Html.BeginForm())
{
<input id="Submit1" type="submit" value="submit" />
}
</body>
</html>

simply use either GET or POST method in your Controller according to your form method like,
[HttpGet]
public ActionResult Index(string id)
{
myc.tp = id;
return View(myc);
}

In your HttpPost you can get the model and see it's properties if you provided input fields for the properties in your view.
[HttpPost]
public ActionResult Index(myclass myc)
{
//check the myc properties here
return View(myc);
}
Then in your View:
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.tp)

Related

Validation in mvc4 not taking place

MODEL
public class SearchTerm
{
[Required(ErrorMessage="please enter")]
public string SearchTrm { get; set; }
}
View
#using (#Html.BeginForm())
{
#Html.ValidationSummary();
#Html.AntiForgeryToken();
....
#Html.TextBoxFor(m=>m.SearchTrm)</span>
<input type="submit" value="Search"/>
#Html.ValidationMessageFor(m=>m.SearchTrm)
#using (Html.BeginForm("Search","Home"))
{
#Html.DropDownList("SelectedFieldId", new SelectList(Model.Fields, "FieldID", "NiceName", Model.SelectedFieldId));
}
}
controller
[HttpPost]
public ActionResult Search(SearchTerm Model)
{
// some code here....
}
When i click a empty search I want the validation message to take place but instead page is getting postback and i am having NullReferenceException
Mention the script name, #section scripts { ...} and check whether jqueryval has 2 files - ~/scripts/jquery.validate.min.js","~/scripts/jquery.validate.unobtrusive.min.js","~/scripts

Having trouble getting my dropdownlist to display in my view

I am basically trying to display a dropdownlist on my data entry view, and the dropdownlist keeps giving me the error "An expression tree may not contain a dynamic operation". I have added "#Model MyModel" to the top of my view, but still can't get past this error. Does anyone have an idea of how to resolve this issue? I have a controller that looks like this
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class MyController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult EnterInfo()
{
GetUT myGetUT = new GetUT();
ViewBag.uts = GetOptions();
return View(myGetUT);
}
[HttpPost]
public ActionResult EnterInfo(GetUT myGetUT)
{
ViewBag.uts = GetOptions();
return View(myGetUT);
}
private List<UT> GetOptions()
{
List<UT> uts = new List<UT>();
uts.Add(new UT() { ID = 1, Name = "1st" });
uts.Add(new UT() { ID = 2, Name = "2nd" });
uts.Add(new UT() { ID = 3, Name = "3rd" });
uts.Add(new UT() { ID = 4, Name = "4th" });
return uts;
}
}
}
and a view that looks like
#Model MyModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>EnterInfo</title>
</head>
<body>
<div>
#Html.DropDownListFor(x => x.UTID, new SelectList(ViewBag.uts, "ID", "Name", Model.UTID))
Enter an Amount :-<input type="text" name="Amount" /><br />
<input type="submit" value="Submit Info" />
</div>
</body>
</html>
Thanks for all the help.
Well, ViewBag is a dynamic type, so I assume that is what it is complaining about. Try putting public List<UT> UTs { get; set; } as a property on MyModel and change your helper to use the UTs property from your model. Like this:
Controller:
public ActionResult EnterInfo()
{
GetUT myGetUT = new GetUT();
myGetUT.UTs = GetOptions();
return View(myGetUT);
}
View:
#Html.DropDownListFor(x => x.UTID,
new SelectList(Model.UTs, "ID", "Name", Model.UTID))`
Edit: If it isn't obvious, your view should be typed to a GetUT type (because that's what you are passing in to the View() function in the EnterInfo action) - I assume that's what you mean when you said #Model MyModel. If not, change it to #Model GetUT and put the property on the GetUT class.

How to Implement MVC3 Model URL Validation?

I've successfully implemented client side validation to require input in my textbox. However, I want to evaluate the contents of the textbox to see if it is a well formed URL. Here's what I have thus far:
Index.cshtml:
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.5.1.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.validate.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>
#model Ticket911.Models.ValidationModel
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
#using (Ajax.BeginForm("Form", new AjaxOptions() { UpdateTargetId = "FormContainer" , OnSuccess = "$.validator.unobtrusive.parse('form');" }))
{
<p>
Error Message: #Html.ValidationMessageFor(m => m.URL)
</p>
<p>
#Html.LabelFor(m =>m.URL):
#Html.EditorFor(m => m.URL)
</p>
<input type="submit" value="Submit" />
ValidationModel:
public class ValidURLAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
return (value != null);
}
}
public class ValidationModel
{
[Required]
public string URL {get; set;}
}
How do I ensure that the model URL validation occurs? When the Submit button is clicked, what must be done to navigate to the URL entered into the textbox?
Thanks much:)
good way is to implement your attribute for next use in mvc projects. like this:
public class UrlAttribute : RegularExpressionAttribute
{
public UrlAttribute() : base(#"^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$")
{}
}
so on the model:
[Url(ErrorMessage = "URL format is wrong!")]
public string BlogAddress { get; set; }
You can do it wtih DataAnnotations
public class ValidationModel
{
[Required]
[RegularExpression(#"^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$", ErrorMessage = "URL format is wrong")]
public string URL {get; set;}
}
And in your HTTPPost Action method, You can call the ModelState.IsValid property which will check the Validations for you.
[HttpPost]
public ActionResult Save(ValidationModel model)
{
if(ModelState.IsValid)
{
//Save or whatever
}
return View(model);
}

asp.net mvc add and hide error for input via ModelState

Is it possible to add an error for input via ModelState.AddModelError(inputId) to have error highlight on UI and to have it to have to behave as like client validation, i.e. when user changes smth in the input error class would be removed.
Model:
public class MyViewModel
{
[Required]
public string Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ModelState.AddModelError("foo", "Foo is required");
return View(new MyViewModel());
}
}
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.Foo)
#Html.ValidationMessageFor(x => x.Foo)
<button type="submit">OK</button>
}
Now when the page is rendered, the Foo field will be highlighted red with an error and when the user types something into the field and blurs out, the error will be removed.

Have to double submit when using Remote attribute based validation

We have a field on our model which has a [Remote] attribute. When we store that field on a Hidden form element and then try to submit that form we have to click the submit button twice. Also interesting is that the 2nd time we click it no remote validation is occurring (so says Fiddler).
Thoughts?
Unable to repro. If the hidden field is decorated with the Remote attribute you won't be able to submit the form no matter how many times you click on the submit button if the remote function sends false.
For example:
Model:
public class MyViewModel
{
[HiddenInput(DisplayValue = false)]
[Remote("Check", "Home")]
public string Id { get; set; }
[Required]
public string Name { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Id = "1"
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
public ActionResult Check(string Id)
{
return Json(Id == "2", JsonRequestBehavior.AllowGet);
}
}
View:
#model AppName.Models.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.EditorForModel()
<input type="submit" value="OK" />
}
Because the remote function will always return false this form cannot be submitted. If the remote function returns true a single click would be enough to submit it assuming of course that the other validation passed.

Resources