I'm struggling to learn how .net mvc works. I've been trying to make sort of a anagram checker, but before that i'm making an input and send through GET (form) to the controller, and want to check for a word if it's equal with another( ex word1 == word1). and if that's true i want to send back to the view 'success' as a string to be written in a label. So i have a question. First i know how to send data through get and so far i checked if a word is equal with something and if that's true then i redirected to index. What i don't know if how can i send that 'success' back to the same view (without ajax if possible) and to write it in a label so i input a text and if that's equal with mine then it will say success under The controller:
{
if ( word == "word1")
{
//return HttpNotFound();
return RedirectToAction("Index");
}
return View();
}
the view:
@{
ViewBag.Title = "CheckAnagram";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>CheckAnagram</h2>
@using (Html.BeginForm("CheckAnagram", "Anagrams", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
{
<div class="form-group">
@Html.TextBox("word", null, new { @class = "form-control", @placeholder = "Check for anagrams" })
</div>
<button type="submit" class="btn btn-default">Submit</button>
}
i know i can send a model to view but then when i reload the page it will send it again, so i can't understand how to make this work properly, what is the normal way to do it?
You can use TempData
to pass model data to a redirect request. You can pass simple types like string, int, Guid etc. If you want to pass a complex type object via TempData, you have can serialize your object to a string and pass that. In your scenario, you can do this:
{
if ( word == "word1")
{
TempData["myresult"] = "Word match";
//return HttpNotFound();
return RedirectToAction("Index");
}
return View();
}
And your Index
method will look like:
public ActionResult Index()
{
if (TempData["myresult"] !=null)
{
var myresult= TempData["myresult"];
ViewBag.myresult=myresult;
}
return View();
}
And in your Index
view, you can simply retrieve the ViewBag
value to be displayed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.